可能重複:
Get difference from two lists in Python從列表在Python列表中移除
什麼是這樣做的一個簡單的方法是什麼?我一直在努力,而且我無法弄清楚。 列表a和列表b,新列表應該只包含列表a中的項目。所以:
a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon
我試過編寫代碼,但每次總是將整個列表返回給我。
可能重複:
Get difference from two lists in Python從列表在Python列表中移除
什麼是這樣做的一個簡單的方法是什麼?我一直在努力,而且我無法弄清楚。 列表a和列表b,新列表應該只包含列表a中的項目。所以:
a = apple, carrot, lemon
b = pineapple, apple, tomato
new_list = carrot, lemon
我試過編寫代碼,但每次總是將整個列表返回給我。
這會幫你嗎?
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)
您可以使用list comprehension這就告訴我們毫不誇張的元素需要new_list
落得寫一個for循環:
new_list = []
for fruit in a:
if fruit not in b:
new_list.append(fruit)
正如你所看到的,這些方法非常相似,這就是爲什麼Python也有列表解析來輕鬆構造列表的原因。
您可能希望這樣:
a = ["apple", "carrot", "lemon"]
b = ["pineapple", "apple", "tomato"]
new_list = [x for x in a if (x not in b)]
print new_list
您可以使用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指出,如果a
和b
做這種方法只適用不包含重複項,並且元素的順序不重要。
我想這是要走的路,但如果它複製了字符串它改變了列表中。 – iurisilvio 2012-07-11 14:23:52
@iurisilvio:你說得對。只有'a'和'b'只包含唯一條目時,這種方法纔有效。在這種情況下,無論如何,對'a','b'使用'set'會更有意義。但是,這可能是最快的方法。 – 2012-07-11 14:30:29
如果這些項目的順序很重要,這也不起作用,但這裏可能不是這樣(我的+1) – mgilson 2012-07-11 14:33:32