<p>您应该使用<a href="https://docs.python.org/2/library/sets.html" rel="nofollow noreferrer">set</a>,而不是列表。
这样可以避免重复,并以方便的方式提供所有操作:</p>
<pre><code>a=[1,2,3,4,5]
b=[1,2,3]
a=set(a)
b=set(b)
# OR
a | b # [1,2,3,4,5]
# AND
a & b # [1,2,3]
# NOT
a - b # [4,5]
</code></pre>
<p>甚至对于复杂的数据类型也可以使用它。他们需要满足两个标准:</p>
<ul>
<li><code>__eq__</code>需要实现</li>
<li><code>__hash__</code>需要实现</li>
</ul>
<p>集合需要<code>__eq__</code>来查找重复项。但是如果您只实现<code>__eq__</code>,那么默认的<code>__hash__</code>实现将被删除。你知道吗</p>
<p>那是因为<code>__eq__</code>和<code>__hash__</code>需要一致。
所以你需要重新实现<code>__hash__</code></p>
<p>实际上,使用内置函数比使用hashlib的版本要好得多。所以我更新了。
令人惊讶的是,<code>__hash__</code>的实现并没有提供<code>__eq__</code>的隐式实现,尽管具有相同散列的对象必须相等是不变量。因此,<code>__eq__</code>和<code>__hash__</code>都需要实现。这在以前版本的答案中是错误的。你知道吗</p>
<p>由于性能原因,<code>__eq__</code>操作符可能需要再次实现。我不知道<code>hash()</code>函数的速度有多快,但是如果集合变大,那么直接比较名称可能是一种有用的优化方法,而不是先对它们进行散列。你知道吗</p>
<pre><code>class Person:
def __init__(self, name):
# assume the 'name' as unique
self.name = name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self.name == other.name
# return hash(self) == hash(other)
def __repr__(self):
return self.name
persons = [Person("a"), Person("b"), Person("a")]
print(persons) # [a, b, a]
persons_set= set(persons)
print(persons_set) # [a, b]
</code></pre>