一文看懂Python中的集合运算&,|,
关于集合的概念
Python 中常用的集合方法是执行标准的数学运算,例如:求并集、交集、差集以及对称差。下图显示了一些在集合 A 和集合 B 上进行的标准数学运算。每个韦恩(Venn)图中的红色部分是给定集合运算得到的结果。
Python中相应符号:
&
符号在Python中既可以执行通常的按位与运算,也可以执行set
集合里面的交集运算|
:并集;也可以表示数字运算中的按位或运算-
:差集^
:对称差集
举例
pre = ["berry","grape","pea_r","apple","banana","pear"]
pos = ["apple","banana","pear","potato","cucumber"]
pre_set = set(pre) # 转换list为集合set
pos_set = set(pos)
union = pos_set | pre_set # 并集
print('The union of the two sets above is:\n{}\n'.format(union))
intersection = pos_set & pre_set # 交集
print('The intersection of two sets is:\n{}\n'.format(intersection))
only_in_preset = pre_set - pos_set # 差集
print('The unique part in pre_set is:\n{}\n'.format(only_in_preset))
only_in_posset = pos_set - pre_set # 差集
print('The unique part in pos_set is:\n{}\n'.format(only_in_posset))
sym_set_diff = pos_set^pre_set # 对称差集
print('The symmetric set difference of the two sets is:\n{}'.format(sym_set_diff))
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
输出结果如下:
The union of the two sets above is:
{'potato', 'grape', 'banana', 'pear', 'berry', 'pea_r', 'cucumber', 'apple'}
The intersection of two sets is:
{'pear', 'apple', 'banana'}
The unique part in pre_set is:
{'berry', 'grape', 'pea_r'}
The unique part in pos_set is:
{'potato', 'cucumber'}
The symmetric set difference of the two sets is:
{'potato', 'pea_r', 'berry', 'cucumber', 'grape'}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
赞 (0)