Python求两个列表的差集,并集,交集
Python中经常需要对两个列表求差集,并集和交集,方法如下:
1,差集
a = [1,2,3,4]
b = [2,3,4,5]
re = [ i for i in a if i not in b ]
# 方法二
re = list(set(a) ^ set(b))
# 方法三
re = list(set(b).difference(set(a)))
2, 并集
re = list(set(a).union(set(b)))
3, 交集
re = list(set(a).intersection(set(b)))