Reputation: 129
How can I compare two list of Objects?
This is the definition of 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;
Now I've two different list of this Object "Form". How can I compare that? I've to found:
Thank you.
Upvotes: 0
Views: 150
Reputation: 5286
The last 2 options you want to compare are the same, if you are comparing two items and the names are different, you both are different from the other.
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")
Will output:
They are the same Form
They have the same name but different value
They have different names
Upvotes: 2