python set集合运算(交集,并集,差集,对称差集)

£神魔★判官ぃ 2024-02-18 23:55 128阅读 0赞

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的子集
True

x.issuperset(z)#x是z的超集
True

" class="reference-link">下面的图片形象地展示了set集合的各种运算: 在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,128人围观)

还没有评论,来说两句吧...

相关阅读