2012-07-11 53 views
19

可能重複:
Get difference from two lists in Python從列表在Python列表中移除

什麼是這樣做的一個簡單的方法是什麼?我一直在努力,而且我無法弄清楚。 列表a和列表b,新列表應該只包含列表a中的項目。所以:

a = apple, carrot, lemon 
b = pineapple, apple, tomato 
new_list = carrot, lemon 

我試過編寫代碼,但每次總是將整個列表返回給我。

回答

5

這會幫你嗎?

a = ["apple", "carrot", "lemon"] 
b = ["pineapple", "apple", "tomato"] 

new_list = [] 
for v in a: 
    if v not in b: 
     new_list.append(v) 

print new_list 

或者,更簡潔:使用

a = ['apple', 'carrot', 'lemon'] 
b = ['pineapple', 'apple', 'tomato'] 

# This gives us: new_list = ['carrot' , 'lemon'] 
new_list = [fruit for fruit in a if fruit not in b] 

或者:

new_list = filter(lambda v: v not in b, a) 
21

您可以使用list comprehension這就告訴我們毫不誇張的元素需要new_list落得寫一個for循環:

new_list = [] 
for fruit in a: 
    if fruit not in b: 
     new_list.append(fruit) 

正如你所看到的,這些方法非常相似,這就是爲什麼Python也有列表解析來輕鬆構造列表的原因。

3

您可能希望這樣:

a = ["apple", "carrot", "lemon"] 
b = ["pineapple", "apple", "tomato"] 

new_list = [x for x in a if (x not in b)] 

print new_list 
13

您可以使用set

# Assume a, b are Python lists 

# Create sets of a,b 
setA = set(a) 
setB = set(b) 

# Get new set with elements that are only in a but not in b 
onlyInA = setA.difference(b) 

UPDATE
作爲iurisilvio和mgilson指出,如果ab做這種方法只適用不包含重複項,並且元素的順序不重要。

+0

我想這是要走的路,但如果它複製了字符串它改變了列表中。 – iurisilvio 2012-07-11 14:23:52

+1

@iurisilvio:你說得對。只有'a'和'b'只包含唯一條目時,這種方法纔有效。在這種情況下,無論如何,對'a','b'使用'set'會更有意義。但是,這可能是最快的方法。 – 2012-07-11 14:30:29

+0

如果這些項目的順序很重要,這也不起作用,但這裏可能不是這樣(我的+1) – mgilson 2012-07-11 14:33:32

2

如何使用sets(或者自從Sets中的set內置於2.6中棄用)?

from sets import Set 
a = Set(['apple', 'carrot', 'lemon']) 
b = Set(['pineapple','apple','tomato']) 
new_set = a.difference(b) 
print new_set 

使輸出

Set(['carrot', 'lemon']) 
+0

爲什麼不使用內建'set'? – mgilson 2012-07-11 14:27:28

+0

我從[python docs](http://docs.python.org/library/sets.html#sets.Set)的例子中得到了這個,但我不知道他們爲什麼這麼做,有什麼想法? – StuGrey 2012-07-11 14:32:50

+0

'sets'自Python v2.6開始被棄用(請參閱http://docs.python.org/library/sets.html) – 2012-07-11 14:33:58