python set集合运算(交集,并集,差集,对称差集)
1》交集
x={1,2,3,4}
y={3,4,5,6}
x
set([1, 2, 3, 4])y
set([3, 4, 5, 6])x&y
set([3, 4])x.intersection(y)
set([3, 4])
2》并集x | y #集合并集
set([1, 2, 3, 4, 5, 6])x.union(y)
set([1, 2, 3, 4, 5, 6])
3》差集x-y # x与y的差集
set([1, 2])x.difference(y)# x与y的差集
set([1, 2])y-x # y与x的差集
set([5, 6])y.difference(x)# y与x的差集
set([5, 6])
4》对称差集x^y
set([1, 2, 5, 6])y^x
set([1, 2, 5, 6])x.symmetric_difference(y)
set([1, 2, 5, 6])y.symmetric_difference(x)
set([1, 2, 5, 6])
5》集合的子集和超集x
set([1, 2, 3, 4])z
set([1, 2, 3])z.issubset(x)#z是x的子集
Truex.issuperset(z)#x是z的超集
True
还没有评论,来说两句吧...