原文地址:https://www.jianshu.com/p/1109e22b50c6
在python3對列表的處理中,會經常使用到Python求兩個list的差集、交集與並集的方法。
一.兩個list差集
如有下面兩個數組:
a = [1,2,3]
b = [2,3]
想要的結果是[1]
下面記錄一下三種實現方式:
1. 正常的方式
ret = [] for i in a: if i not in b: ret.append(i)
2.簡化版
ret = [ i for i in a if i not in b]
3.高級版
ret = list(set(a) ^ set(b))
4.最終版
print(list(set(b).difference(set(a)))# b中有而a中沒有的
二.兩個list並集
print(list(set(a).union(set(b))))
三.兩個list交集
print(list(set(a).intersection(set(b))))