以下是一个比较两个复杂对象列表的示例代码:
class ComplexObject:
def __init__(self, id, name):
self.id = id
self.name = name
def __eq__(self, other):
if isinstance(other, ComplexObject):
return self.id == other.id and self.name == other.name
return False
def __ne__(self, other):
return not self.__eq__(other)
def compare_lists(list1, list2):
# 对比列表长度
if len(list1) != len(list2):
return False
# 对比列表中的每个对象
for obj1, obj2 in zip(list1, list2):
if obj1 != obj2:
return False
return True
# 创建复杂对象列表
list1 = [ComplexObject(1, 'obj1'), ComplexObject(2, 'obj2'), ComplexObject(3, 'obj3')]
list2 = [ComplexObject(1, 'obj1'), ComplexObject(2, 'obj2'), ComplexObject(3, 'obj3')]
# 比较两个列表
result = compare_lists(list1, list2)
print(result) # 输出 True
在上面的示例中,我们首先定义了一个ComplexObject
类,该类具有两个属性id
和name
,并且重写了__eq__
和__ne__
方法来定义对象的相等性。然后我们定义了一个compare_lists
函数来比较两个复杂对象列表。这个函数首先检查两个列表的长度是否相等,如果不相等,则返回False
。然后它使用zip
函数迭代两个列表中的对象,并使用!=
运算符比较它们是否相等。如果有任何不相等的对象,函数将返回False
。如果两个列表中的所有对象都相等,则函数返回True
。
最后,我们创建了两个相同的复杂对象列表,并调用compare_lists
函数来比较它们。最终的结果是True
,表示两个列表是相等的。
上一篇:比较两个复杂的字符串数组列表
下一篇:比较两个GDB-Core转储文件