2012-08-24 55 views
1

我试图找到2个列表之间的区别。基本上,我想知道的一切,这是在列表1不在列表2来解释它的最好办法,是用一个例子:如何比较2个列表并返回差异? (Python中的差异函数不会返回我需要的)

List1 = [a, a, b, c, d, e] 
List2 = [a, b, c, d] 

In this example, I would like a function that would return [a, e] 

当我在Python中使用的不同的功能,它不仅会返回“e”,而不是列表1中有一个额外的“a”。当我简单地在两个列表之间使用XOR时,它也只返回“e”。

+0

顺序对您是否重要? – DSM

+0

顺序无关紧要。谢谢! – user1618063

回答

8

你想要的是真的不设置减法。您可以使用Counter

>>> List1 = ['a', 'a', 'b', 'c', 'd', 'e'] 
>>> List2 = ['a', 'b', 'c', 'd'] 
>>> import collections 
>>> counter = collections.Counter(List1) 
>>> counter.subtract(List2) 
>>> list(counter.elements()) 
['a', 'e'] 
+0

那么,至少我可以添加这么多:'Counter(List1)-Counter(List2)'也可以。我们在这里很幸运,因为OP只希望1中的成员不在2中(否则减法将在2中失去'f')。 – DSM

+0

我不确定我是否遵循 - 什么情况下''.subtract''与'Counter-Counter''不同? – jterrace

+0

@jterrace - 'subtract'不需要赋予'Counter'的实例。它主要是读取代码的方式:'Counter(List1).subtract(List2)'vs'Counter(List1) - Counter(List2)'。第一种情况可能会有一些(小的)性能提升,但第二种情况可能稍微好一些? – mgilson

1

假设List1List2一个严格的超:

for i in List2: 
    if i in List1: 
     List1.remove(i) 
# List1 is now ["a", "e"] 

(您可以克隆List1,如果你不想做它在的地方。)

+0

这似乎是'try/except'的地方。没有意义在List1中查找两次。 – mgilson

+0

这一个很容易为我工作。非常感谢你的提交! – user1618063

相关问题