版权声明:本文为转载文章,原文地址:https://blog.csdn.net/sxingming/article/details/51922776点击打开链接

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

下面的图片形象地展示了set集合的各种运算:
python set集合运算(交集,并集,差集,对称差集)

(完)


相关文章:

  • 2021-12-14
  • 2021-11-17
  • 2021-12-25
  • 2021-11-16
  • 2022-12-23
  • 2021-11-06
猜你喜欢
  • 2021-09-02
  • 2021-07-17
  • 2022-02-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-10
相关资源
相似解决方案