忽略顺序比较列表的内容

Comparing contents of lists ignoring order

假设我有一个 class 如下所示:

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 个对象。有没有人有快速有效的方法来解决这个问题?谢谢!

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

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

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

如何证明 x 和 y 相同?

您需要实现 __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

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

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