关于python取list的交集,差集,并集
交集
- 直接用循环取
a = [2,3,4,5]
b = [2,5,8]
tmp = [val for val in a if val in b]
- 使用list的intersection方法
a=[2,3,4,5]
b=[2,5,8]
tmp = list(set(a).intersection(set(b))) # 两者都有的元素
差集
- 直接用循环取
a = [2,3,4,5]
b = [2,5,8]
tmp = [val for val in a if val not in b]
- 使用list的difference方法
a = [2,3,4,5]
b = [2,5,8]
tem = list(set(a).difference(set(b))) # a中有,b中没有
并集
tem = list(set(a).union(set(b))) # 合并两个list,且不重复