python兩個 list 獲取交集,並集,差集的方法

1. 獲取兩個list 的交集spa

#方法一:
a=[2,3,4,5]
b=[2,5,8]
tmp = [val for val in a if val in b]
print tmp
#[2, 5]

#方法二
print list(set(a).intersection(set(b)))

2. 獲取兩個list 的並集code

print list(set(a).union(set(b)))

3. 獲取兩個 list 的差集blog

print list(set(b).difference(set(a))) # b中有而a中沒有的      很是高效!
相關文章
相關標籤/搜索