可能重复:
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