2012-07-11 85 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