首页 > 解决方案 > Python比较和区分自定义对象

问题描述

如何比较两个对象列表?

这是对象的定义:

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;

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

谢谢你。

标签: pythonlistobjectcompare

解决方案


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

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

推荐阅读