gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:48 24 4
gpt4 key购买 nike

我试图找出两个列表之间的区别。基本上,我想知道列表 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']

关于python - 你如何比较 2 个列表并返回差异? (python 中的差异函数不返回我需要的东西),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12114668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com