【问题标题】:Python compare and diff custom objectPython比较和区分自定义对象
【发布时间】:2020-10-19 09:44:58
【问题描述】:

如何比较两个对象列表?

这是Object的定义:

class Form:
    def __init__(self,name, value):
        self.name = name;
        self.value = value;
        
    def __eq__(self, other):
        return self.name == other.name and self.value == other.value;

现在我有两个不同的对象“表单”列表。我怎么能比较呢?我必须找到:

  • 名称和值相同
  • 名称相同但值不同
  • 名称与第一个列表不同
  • 名称与第二个列表不同

谢谢。

【问题讨论】:

  • 你不能为 Python 中的单个对象提供多个相等条件,当它们名称相等时,wither 实例是相等的,或者当它们的名称和值都相等时实例是相等的,但是你 nca' t 同时拥有两者。所以你需要手动检查它们。
  • 另外,您必须考虑列表长度不同的情况。

标签: python list object compare


【解决方案1】:

你要比较的最后两个选项是相同的,如果你在比较两个项目并且名称不同,那么你们两个都是不同的。

lst_1 = [Form('a', 1), Form('b', 2), Form('c', 3)]
lst_2 = [Form('a', 1), Form('b', 0), Form('d', 3)]

if len(lst_1) != len(lst_2):
    print("WARNING: lists are of different sizes, checking the first elements")
for a, b in zip(lst_1, lst_2):
    if not isinstance(a, Form) or not isinstance(b, Form):
        raise TypeError
    if a == b:  # Both name and valua are equal
        print("They are the same Form")
    elif a.name == b.name:  # Only names are equal
        print("They have the same name but different value")
    else:  # Names are different
        print("They have different names")

将输出:

They are the same Form
They have the same name but different value
They have different names

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 2016-11-20
    相关资源
    最近更新 更多