交集Intersection: intersection() and &;
1. With the fun of intersection()
>>> first_set = set([’CP0140.1’,’EF3613.1’,’EF3616.1’])
>>> other_set = set([’CP0140.2’,’EF3613.1’,’EF3616.2’])
>>> common = first_set.intersection(other_set)
>>> common
set([’EF3613.1’])
2. Instead of intersection(), it is possible to use the shortcut &:
>>> common = first_set & other_set
>>> common
set([’EF3613.1’])
image.png
并集Union: The union of two (or more) sets is the operator union and its abbreviated form is | ;
>>> first_set.union(other_set)
set([’EF3616.2’, ’EF3613.1’, ’EF3616.1’, ’CP0140.1’, ’CP0140.2’])
>>> first_set | other_set
set([’EF3616.2’, ’EF3613.1’, ’EF3616.1’, ’CP0140.1’, ’CP0140.2’])
image.png
Difference (in one,仅出现在一组中不一样的地方) : A difference is the resulting set of elements that belongs to one set but not to the other. Its shorthand is −:
>>> first_set.difference(other_set)
set([’CP0140.1’, ’EF3616.1’])
>>> first_set - other_set
set([’CP0140.1’, ’EF3616.1’])
image.png
Symmetric difference (in both两组中都不一样的地方) : A symmetric difference refers to those elements that are not a part of the intersection; its operator is symmetric difference and it is shorted as ˆ ;【A与B交集的补集】
>>> first_set.symmetric_difference(other_set)
set([’EF3616.2’, ’CP0140.1’, ’CP0140.2’, ’EF3616.1’])
>>> first_set ^ other_set
set([’EF3616.2’, ’CP0140.1’, ’CP0140.2’, ’EF3616.1’])
image.png
Set to list: set对象可以通过以下代码转为list,经测试,list也可以进行上述操作计算:
>>> first_set = set([’CP0140.1’,’EF3613.1’,’EF3616.1’])
>>> list(first_set)
[’EF3616.1’, ’EF3613.1’, ’CP0140.1’]
结合以上处理,你就可以轻易处理很多python中list的转换计算等操作了!!!
网友评论