问题描述
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,c]
y = [d,b]
sorted([id(temp) for temp in x]) == sorted([id(temp) for temp in y])
Output: False
,
您可以根据您的属性 sorted()
比较 A
的 2 个替代列表:
>>>print(sorted([o.A for o in a]) == sorted([o.A for o in b]))
True