# ### 集合相关操作 (交差并补) #intersection() 交集 set1 = {"周杰伦","王文","刘德华"} set2 = {"周润发","周星星","王文"} res = set1.intersection(set2) print(res) res = set1 & set2 print(res) #difference() 差集 set1= {"方贵权","黄一真","黄少正","黄熊大","皇阿玛"} set2 = {"邓远文","王俊文","黄文","黄熊大"} res = set1.difference(set2) print(res) res = set1 - set2 print(res) #union() 并集 set1= {"方贵权","黄一真","黄少正","黄熊大","皇阿玛"} set2 = {"邓远文","王俊文","黄文","黄熊大"} res = set1.union(set2) print(res) res = set1 | set2 print(res) #symmetric_difference() 对称差集 (补集情况涵盖在其中) set1= {"方贵权","黄一真","黄少正","黄熊大","皇阿玛"} set2 = {"邓远文","王俊文","黄文","黄熊大"} res = set1.symmetric_difference(set2) print(res) res = set1 ^ set2 print(res) #issubset() 判断是否是子集 set1 = {"王文","王俊文","黄文"} # set2 = {"王文","王俊文","黄文"} set2 = {"黄文"} res = set2.issubset(set1) print(res) # 真子集:2个集合不是完全一样的 res =set2 < set1 # <= print(res) #issuperset() 判断是否是父集 set1 = {"王文","王俊文","黄文"} set2 = {"黄文"} res = set1.issuperset(set2) print(res) res = set1 > set2 # >= print(res) #isdisjoint() 检测两集合是否不相交 不相交 True 相交False set1 = {"王文","王俊文","黄文"} set2 = {"黄文"} res = set1.isdisjoint(set2) print(res) # ### 集合相关函数 # (1) 增 #add() 向集合中添加数据 setvar = {"王文","王俊文","黄文"} setvar.add("张耀文") print(setvar) #update() 迭代着增加 update(可迭代性数据) setvar.update(["陈文江","姜文"]) print(setvar) # (2) 删除 #clear() 清空集合 setvar = {"王文","王俊文","黄文"} setvar.clear() print(setvar) #pop() 随机删除集合中的一个数据 setvar = {"王文","王俊文","黄文"} setvar.pop() print(setvar) #remove() 删除集合中指定的值(不存在则报错) setvar = {"王文","王俊文","黄文"} setvar.remove("黄文") # setvar.remove("黄133文") error print(setvar) #discard() 删除集合中指定的值(不存在的不删除 推荐使用) setvar = {"王文","王俊文","黄文"} res = setvar.discard("黄133文") print(setvar) # print(res) # ###冰冻集合 (只能做交叉并补) # frozenset 可强转容器类型数据变为冰冻集合 # 冰冻集合一旦创建,不能在进行任何修改,只能做交叉并补操作 # (1) 声明空的冰冻集合 fz = frozenset() print(fz,type(fz)) fz1 = frozenset([1,2,3,4]) print(fz1,type(fz1)) # fz2 = frozenset("2345") fz2 = frozenset((2,3,4,5)) print(fz2,type(fz2)) res = fz1 & fz2 print(res) # fz1.add("890") # error 不允许添加或者删除操作.
原文地址:https://www.cnblogs.com/huangjiangyong/p/10823131.html
时间: 2024-10-10 10:01:45