欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python的集合操作总结

程序员文章站 2022-06-06 18:37:40
...
a=set([1,2,3,4,5,6])
b=set([4,5,6,7])
# intersection 交集
#a和b的交集
print(a.intersection(b))#{4, 5, 6}
print(a & b)#{4, 5, 6}

# union  并集
print(a.union(b))#{1, 2, 3, 4, 5, 6, 7}
print(a | b)#{1, 2, 3, 4, 5, 6, 7}  等价于a.union(b)

#difference 差集
print(a.difference(b))#{1, 2, 3}  in a but not in b
print(a - b)#{1, 2, 3}  in a but not in b
print(b.difference(a))#{7}
print(b - a)#{7}
print(a.symmetric_difference(b))#{1, 2, 3, 7}  symmetric 对称差集 除了交集之外的所有
print(a ^ b)#{1, 2, 3, 7}  symmetric 对称差集 除了交集之外的所有

#父集 超集
print(a.issuperset(b))
print(a > b)
#子集
print(a.issubset(b))
print(a < b)