Python3中的唯一类实例

Mac*_*nos 0 python numpy unique

假设我有这样的类定义

class structure:
    def __init__(self, handle):
        self.handle = handle
Run Code Online (Sandbox Code Playgroud)

我如何使用numpy.uniquePython3的另一个工具来查找此类实例列表中的唯一元素?应该根据该'handle'领域的价值进行比较.

Mar*_*ers 6

numpy.unique不是自定义类的最佳工具.使实例可哈希(实现__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
Run Code Online (Sandbox Code Playgroud)

有效集可以通过散列检测重复,确认具有相同散列的对象首先也是相等的.

要获取唯一实例,只需调用set()一系列实例:

unique_structures = set(list_of_structures)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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')>}
Run Code Online (Sandbox Code Playgroud)

请注意,structure存储在集合中或使用字典键的任何实例的散列都不得更改 ; handle在实例的生命周期内不改变属性是确保这一点的最简单方法.