2012-02-17 74 views
4

我試圖找出所有在列表A和不在列表B.Python列表差異

我覺得像newList = list(set(a) & !set(b))newList = list(set(a) & (not set(b)))東西會工作的元素,但它不是。

如果還有更好的方法來實現我想要做的除此之外的事情嗎?

newList = [] 
for item in a: 
    if item not in b: 
     newList.append(item) 

同樣重要的,它需要在Python 2.6

回答

15

您正在尋找的set difference

newList = list(set(a).difference(b)) 

或者,使用減號來:

list(set(a) - set(b)) 
+1

請注意,從列表 - >設置 - >列表的轉換將失去原始列表的排序。 – sirdodger 2012-07-20 21:02:12

10

做你嘗試

list(set(a) - set(b)) 

這裏是所有Python set operations的列表。

但是這會不必要地爲b創建一個新集。正如@phihag提到的,difference方法會阻止這一點。

+0

這不必要地構建了一個集合,你千萬不要擡頭看。 – phihag 2012-02-17 21:41:44

+0

你說得對。我沒有意識到「差異」方法接受任何迭代,而不僅僅是設置。編輯答案。 – 2012-02-17 21:46:37

1

如果你關心維持秩序:

def list_difference(a, b): 
    # returns new list of items in a that are not in b 
    b = set(b) 
    return [x for x in a if x not in b] 
1
>>> list1 = [1,2,3,4,5] 
>>> list2 = [4,5,6,7,8] 
>>> print list(set(list1)-set(list2)) 
[1, 2, 3] 
+0

雖然此代碼可能是正確的,但請提供一些解釋。 – 2015-02-12 07:26:57