Skip to main content
 首页 » 编程设计

python之你如何比较 2 个列表并返回差异 (python 中的差异函数不返回我需要的东西)

2025年05月04日11落叶无声

我试图找出两个列表之间的区别。基本上,我想知道列表 1 中不在列表 2 中的所有内容。最好的解释方法是举个例子:

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 中使用 difference 函数时,它只会返回“e”,而不是列表 1 中有一个额外的“a”。当我简单地在 2 个列表之间使用 XOR 时,它也只返回“电子。”

请您参考如下方法:

你要的真不是集减法。您可以使用 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']