Python 求两个 list 的交集、并集、差集、和集
Python 求两个 list 的交集、并集、差集、和集
此处是对 list 进行运算,而非 set。
import collections
from functools import reduce
a = [1,2,3,3,4]
b = [3,3,4,5,6]
aa = collections.Counter(a)
bb = collections.Counter(b)
intersection = aa & bb # 交集
union = aa | bb # 并集
sub = aa - bb # 差集
add = aa + bb # 和集
for i in [intersection, union, sub, add]:
print(i) # 解集的 dict
print(reduce(lambda x, y: x+y, [[k]*v for k, v in i.items()])) # 解集
输出结果:
# 交集
Counter({3: 2, 4: 1})
[3, 3, 4]
# 并集
Counter({3: 2, 1: 1, 2: 1, 4: 1, 5: 1, 6: 1})
[1, 2, 3, 3, 4, 5, 6]
# 差集
Counter({1: 1, 2: 1})
[1, 2]
# 和集
Counter({3: 4, 4: 2, 1: 1, 2: 1, 5: 1, 6: 1})
[1, 2, 3, 3, 3, 3, 4, 4, 5, 6]