如何从自定义对象列表中删除重复项?

Con*_*ine 3 python list duplicates

我有一个自定义的对象类,具有各种不同类型的属性。我想根据这些属性之一从这些对象的列表中删除重复项。

类似这样,但实际上获取的是对象列表而不是指定属性的列表。

filteredData = list(set([x.attribute[0] for x in objList]))
Run Code Online (Sandbox Code Playgroud)

ceh*_*mja 5

您需要在对象上实现方法hasheq

class A:
    def __init__(self, a):
        self.attr1 = a

    def __hash__(self):
        return hash(self.attr1)

    def __eq__(self, other):
        return self.attr1 == other.attr1

    def __repr__(self):
        return str(self.attr1)
Run Code Online (Sandbox Code Playgroud)

例子:

l = [A(5), A(4), A(4)]
print list(set(l))
print list(set(l))[0].__class__  # ==> __main__.A. It's a object of class
Run Code Online (Sandbox Code Playgroud)