【问题标题】:How do you compare 2 lists and return the difference? (difference function in python does not return what I need)您如何比较 2 个列表并返回差异? (python中的差异函数不返回我需要的)
【发布时间】:2012-08-24 18:17:51
【问题描述】:

我正在尝试找出 2 个列表之间的区别。基本上,我想知道列表 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中使用差异函数时,它只会返回“e”,而不是列表1中有一个额外的“a”。当我在2个列表之间简单地使用XOR时,它也只返回“ e.”

【问题讨论】:

  • 顺序无关紧要。谢谢!

标签: python list compare


【解决方案1】:

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

【讨论】:

  • 好吧,至少我可以补充这么多:Counter(List1)-Counter(List2) 也可以。我们在这里很幸运,因为 OP 只想要 1 而不是 2 的成员(否则减法会在 2 中丢失“f”)。
  • 我不确定我是否遵循 - .subtract 与 Counter-Counter 有什么不同?
  • @jterrace -- subtract 不需要提供Counter 的实例。这主要取决于如何读取代码:Counter(List1).subtract(List2) vs Counter(List1) - Counter(List2)。在第一种情况下可能会有一些(小的)性能提升,但第二种情况可能更容易阅读?
  • 感谢您的回复!我是一名新程序员,所以当我尝试使用此代码时,我不断收到此错误:“AttributeError: 'module' object has no attribute 'Counter' - 你知道我做错了什么吗?谢谢!!跨度>
  • jterrace:是的,它只是一种风格。没什么大不了的,你只是打败了我。 :^) @user1618063: 啊,那你一定是在使用旧版本的 Python,pre-2.7。如果可能,您应该升级;人们将在他们的 SO 答案中使用 2.7 中有很多不错的功能。 [升级到 3.2 仍然有点问题,因为并非所有库都支持它,但这逐渐变得不那么问题了。]
【解决方案2】:

假设List1 是List2 的严格超集:

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

(如果您不想就地操作,可以克隆 List1。)

【讨论】:

  • 这似乎是try/except 的地方。在 List1 中查找该项目两次是没有意义的。
猜你喜欢
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
  • 1970-01-01
  • 2013-08-08
  • 1970-01-01
  • 2020-04-02
相关资源
最近更新 更多