2012-02-17 90 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