【问题标题】:Comparing contents of lists ignoring order比较列表的内容忽略顺序
【发布时间】:2021-08-31 08:44:45
【问题描述】:

假设我有一个如下所示的类:

class OBJ:
    def __init__(self, a):
        self.A = a

我有 2 个这些对象的列表

# sorry this is a bad example, plz look at the bottom
a = [OBJ(1), OBJ(0), OBJ(20), OBJ(-1)]
b = [OBJ(20), OBJ(-1), OBJ(1), OBJ(0)]

我如何证明这两个列表的内容是相同的? 我曾尝试使用 sorted() 方法,但它似乎不起作用,因为您无法在逻辑上比较 2 个对象。有没有人有快速有效的方法来解决这个问题?谢谢!

编辑: 抱歉,这 2 个列表是一个不好的例子。当我的意思相同时,我的意思是它们都指的是同一个对象。所以:

a = OBJ(1)
b = OBJ(-1)
c = OBJ(20)

x = [a,b,c]
y = [c,a,b]

如何证明 x 和 y 相同?

【问题讨论】:

  • 内容“相同”是什么意思?使用您发布的代码,(OBJ(0) == OBJ(0)) is False
  • 对不起,我的意思是他们应该引用同一个对象,我已经编辑了问题
  • 你的意思是指同一个对象,还是对象有相同的输入?如果您要检查它们是否指向完全相同的对象,我已经编辑了我的答案。

标签: python list equality


【解决方案1】:

您需要实现__eq____lt__ 方法以允许您对对象进行排序然后比较它们:

class OBJ:
    def __init__(self, a):
        self.A = a
    
    def __eq__(self, other): 
        if not isinstance(other, OBJ):
            # don't attempt to compare against unrelated types
            return NotImplemented

        return self.A == other.A
    
    def __lt__(self, other):
         return self.A < other.A

a = [OBJ(1), OBJ(0), OBJ(20), OBJ(-1)]
b = [OBJ(20), OBJ(-1), OBJ(1), OBJ(0)]

测试:

sorted(a) == sorted(b)
Output: True

编辑:

问题中的注释使您想要检查对象是否完全相同,而不仅仅是相同的输入。为此,只需使用id() 来查看它们是否指向同一个确切的对象

示例:

a = OBJ(1)
b = OBJ(-1)
c = OBJ(20)

x = [a,b,c]
y = [c,a,b]
sorted([id(temp) for temp in x]) == sorted([id(temp) for temp in y])
Output: True

不过……

a = OBJ(1)
b = OBJ(-1)
c = OBJ(20)
d = OBJ(20) # Same input value as c, but a different object

x = [a,b,c]
y = [d,a,b]
sorted([id(temp) for temp in x]) == sorted([id(temp) for temp in y])
Output: False

【讨论】:

    【解决方案2】:

    您可以根据您的属性 A 比较两个替代列表 sorted()

    >>>print(sorted([o.A for o in a]) == sorted([o.A for o in b]))
    True
    

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 2023-03-21
      • 2018-08-16
      • 2014-02-21
      • 2012-05-29
      • 2022-01-25
      • 2017-01-06
      • 1970-01-01
      相关资源
      最近更新 更多