php語言

當前位置 /首頁/計算機/php語言/列表

Python求兩個list差集的方法

有時候,為了需求,需要統計兩個 list 之間的交集,並集,差集。下面我們就給大家詳細介紹一下吧!

Python求兩個list差集的方法

  一.兩個list差集

如有下面兩個陣列:

a = [1,2,3]

b = [2,3]

想要的`結果是[1]

下面記錄一下三種實現方式:

1. 正常的方式程式碼如下

ret = []

for i in a:

if i not in b:

nd(i)

2. 濃縮版程式碼如下

ret = [ i for i in a if i not in b ]

3. 另一版程式碼如下

ret = list(set(a) ^ set(b))

  二. 獲取兩個list 的並集程式碼如下

print list(set(a)n(set(b)))

  三. 獲取兩個 list 的差集程式碼如下

print list(set(b)erence(set(a))) # b中有而a中沒有的

TAG標籤:差集 list Python #