【问题标题】:Unique class instances in Python3Python3 中的唯一类实例
【发布时间】:2016-04-01 10:34:35
【问题描述】:

假设我有这样的类定义

class structure:
    def __init__(self, handle):
        self.handle = handle

如何使用numpy.unique 或 Python3 的其他工具在此类的实例列表中查找唯一元素?应根据'handle' 字段的值进行比较。

【问题讨论】:

  • 您想要句柄的值还是实例的值?如果你希望实例和两个实例的句柄值相同,应该选择哪个?

标签: python numpy unique


【解决方案1】:

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 属性是确保这一点的最简单方法。

【讨论】:

  • 能否请您解释一下插入'if not isinstance'的原因?
  • @Macaronnos:像__eq__ 这样的比较方法应该总是返回NotImplemented,因为它们不支持比较;除了structure 实例之外,支持相等性测试没有什么意义。
  • 哦,没错。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 2013-08-19
  • 2018-01-12
  • 1970-01-01
相关资源
最近更新 更多