比较两个自定义列表python

2024-05-29 10:16:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我在比较python中的两个对象列表时遇到了困难

我正在将一条消息转换为

class StatusMessage(object):
    def __init__(self, conversation_id, platform):
        self.__conversation_id = str(conversation_id)
        self.__platform = str(platform)

    @property
    def conversation_id(self):
        return self.__conversation_id

    @property
    def platform(self):
        return self.__platform 

现在,当我创建两个StatusMessage类型的列表时

^{pr2}$

然后我用

>>> cmp(actual, expected) 

或者

>>> len(set(expected_messages_list).difference(actual_list)) == 0

我总是失败。 当我调试并实际比较列表中的每一项时

>>> actual[0].conversation_id == expected[0].conversation_id
>>> actual[0].platform == expected[0].platform

然后我总是看到

True

以下操作返回-1

>>> cmp(actual[0], expected[0])

为什么会这样。我错过了什么???在


Tags: 对象selfid列表returndefpropertylist
2条回答

必须告诉python如何检查StatusMessage类的两个实例是否相等。在

例如,添加方法

def __eq__(self,other):
    return (self is other) or (self.conversation_id, self.platform) == (other.conversation_id, other.platform)

将产生以下效果:

^{pr2}$

如果要将cmpStatusMessage对象一起使用,请考虑实现__lt__和{}方法。我不知道你想用哪个规则来考虑一个实例比另一个实例小或大。在

此外,考虑返回False或错误检查,以便将StatusMessage对象与没有conversation_id或{}属性的任意对象进行比较。{10>否则,}你将得到}:

>>> actual[0] == 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "a.py", line 16, in __eq__
    return (self is other) or (self.conversation_id, self.platform) == (other.conversation_id, other.platform)
AttributeError: 'int' object has no attribute 'conversation_id'

您可以找到self is other检查是个好主意的原因here(在多线程应用程序中可能会出现意外结果)。在

因为要比较两个自定义对象,所以必须定义使对象相等或不相等的因素。为此,可以在StatusMessage类上定义__eq__()方法:

class StatusMessage(object):
    def __eq__(self, other):
        return self.conversation_id == other.conversation_id and
               self.platform == other.platform

相关问题 更多 >

    热门问题