python集合(set)的运算
1.交集
In [1]: a = {1,2,3,4} In [2]: b = {3,4,5,6} In [3]: a & b Out[3]: {3, 4} In [4]: a.intersection(b) Out[4]: {3, 4}
2.并集
In [5]: a | b Out[5]: {1, 2, 3, 4, 5, 6} In [6]: a.union(b) Out[6]: {1, 2, 3, 4, 5, 6}
3.差集
In [9]: a-b Out[9]: {1, 2} In [10]: b-a Out[10]: {5, 6} In [11]: a.difference(b) Out[11]: {1, 2} In [12]: b.difference(a) Out[12]: {5, 6}
4.对称差集
In [13]: a^b Out[13]: {1, 2, 5, 6} In [14]: a.symmetric_difference(b) Out[14]: {1, 2, 5, 6}
5.集合的子集和超集
In [15]: x = {1,2,3,4} In [16]: y = {1,2,3} In [17]: y.issubset(x) Out[17]: True In [18]: x.issuperset(y) Out[18]: True
下面的图片形象地展示了set集合的各种运算:
集合 x <==> ① + ②
集合 x <==> ② + ③
交集 x&6 <==> ②
并集 x|y <==> ① + ② + ③
差集 x-y <==> ①
差集 y-x <==> ③
对称差集 x^y == y^x <==> ① + ③