从列表中删除重复的对象

时间:2019-03-16 22:23:50

标签: python

通过将简单对象列表转换为集合,可以很容易地从简单对象列表中删除重复项:

l = ['Joe','Peter','Paul','Joe','Peter','Paul']
s = set(l)

我尝试了一些更复杂的对象,但是没有成功:

class fullname:

    def __init__(self, firstname, surname):
        self.firstname = firstname
        self.surname = surname

firstnames=['Joe','Peter','Paul','Joe','Peter','Paul']
surnames = ['Miller','Smith','McCartney','Miller','Smith','McCartney']


fullnames = []
for i in range(len(firstnames)):
    fullnames.append(fullname(firstnames[i],surnames[i]))

列表全名包含3对具有相等属性值的对,但是python不会将对象解释为相等。 是否有一种优雅的方法可以从列表中删除复杂对象的重复项(例如,具有相同属性值的对象)?

由于jonrsharpe的提示,我找到了以下解决方案:

class fullname:

    def __init__(self, firstname, surname):
        self.firstname = firstname
        self.surname = surname

    def __eq__(self, other):
        if self.surname == other.surname and self.firstname == other.firstname:
            return True
        else:
            return False

firstnames =['Joe','Peter','Paul','Joe','Peter','Paul']
surnames = ['Miller','Smith','McCartney','Miller','Smith','McCartney']

# create list of objects
fullnames = []
for i in range(len(firstnames)):
    fullnames.append(fullname(firstnames[i],surnames[i]))

# copy singular objects to list nodup
nodup = []
for element in fullnames:
    if element not in nodup:
        nodup.append(element)

for each in nodup:
    print(each.firstname,each.surname)

0 个答案:

没有答案