set1 = {"1","2","3","4"} set2 = {"a","b","c","d,"1","2"}
一、intersection() 交集
res = set1.intersection(set2) print(res) # 简写 & res = set1 & set2 print(res)
二、差集
res = set1.difference(set2) print(res) # 简写 - res = set1 - set2 print(res)
三、并集
res = set1.union(set2) print(res) # 简写 | res = set1 | set2 print(res)
四、symmetric_difference() 对称差集 (补集情况涵盖在其中)
res = set1.symmetric_difference(set2) print(res) # 简写 ^ res = set1 ^ set2 print(res)
五、issubset()判断是否是子集
set1 = {"张三","李四","王五"} set2 = {"张三","王五"} res = set1.issubset(set2) print(res) # 简写 < res = set1 < set2 print(res)
六、issuperset() 判断是否是父集
res = set1.issuperset(set2) print(res) # 简写 > res = set1 > set2 print(res)
七、isdisjoint() 检测两集合是否不相交 不相交 True 相交False
res = set1.isdisjoint(set2) print(res)
八、相关函数
1、add() 向集合中添加数据 (一次加一个) 2、update() 迭代着增加 (一次加一堆) 3、clear() 清空集合 4、pop() 随机删除集合中的一个数据 5、remove() 删除集合中指定的值(不存在则报错) 6、discard() 删除集合中指定的值(不存在的不删除)
九、冰冻集合
#frozenset() 可强转容器类型数据变为冰冻集合 """冰冻集合一旦创建,不能在进行任何修改,只能做交叉并补操作""" lst1 = ["1",2,"3","4"] fz1 = frozenset(lst1) lst2 = ("1","2","3") fz2 = frozenset(lst2) print(fz1 , type(fz1)) print(fz2 , type(fz2)) # 不能够在冰冻集合当中添加或者删除元素 # fz1.add(123) error # 只能交差并补 print( fz1 & fz2 ) print( fz1 - fz2 )
标签:python,res,fz1,print,set1,set2,集合,操作 From: https://www.cnblogs.com/songyunjie/p/16824942.html