set()运算
1 计算两个list的关系时,可转化为set进行运算.
参考:https://www.runoob.com/python3/python3-set.html
a =[1,4,3,5,6,6,7,7,7] b =[2,2,3,3,1,1,22] a = set(a) b = set(b) # a与b的差集 print(a - b) # a与b的交集 print(a & b) print(a.intersection(b)) # a与b的并集 print(a | b) print(a.union(b)) # 不同时包含于a和b的元素,类似于symmetric_difference_update函数 print(a ^ b) # {4, 5, 6, 7} # {1, 3} # {1, 3} # {1, 2, 3, 4, 5, 6, 7, 22} # {1, 2, 3, 4, 5, 6, 7, 22} # {2, 4, 5, 6, 7, 22}
对于list中是字符串的情况同样可以使用
a = ['a','b','c','d'] b = ['a','b','p','q'] print( set(a) & set(b)) # {'a', 'b'}