numpy.unique 不是自定义类的最佳工具。将您的实例设为hashable(实现__hash__ 和__eq__),然后使用集合将实例列表缩减为唯一值:
class structure:
def __init__(self, handle):
self.handle = handle
def __hash__(self):
return hash(self.handle)
def __eq__(self, other):
if not isinstance(other, structure):
# only equality tests to other `structure` instances are supported
return NotImplemented
return self.handle == other.handle
高效的集合可以通过哈希检测重复,首先确认具有相同哈希的对象也相等。
要获得唯一的实例,只需在一系列实例上调用set():
unique_structures = set(list_of_structures)
演示:
>>> class structure:
... def __init__(self, handle):
... self.handle = handle
... def __hash__(self):
... return hash(self.handle)
... def __eq__(self, other):
... if not isinstance(other, structure):
... # only equality tests to other `structure` instances are supported
... return NotImplemented
... return self.handle == other.handle
... def __repr__(self):
... return '<structure({!r})>'.format(self.handle)
...
>>> list_of_structures = [structure('foo'), structure('bar'), structure('foo'), structure('spam'), structure('spam')]
>>> set(list_of_structures)
{<structure('bar')>, <structure('foo')>, <structure('spam')>}
请注意任何structure 实例的哈希值存储在集合中或使用了字典键不得更改;在实例的生命周期内不更改 handle 属性是确保这一点的最简单方法。