使列表可变且可哈希

问题描述 投票:0回答:2

可进行哈希处理的对象需要__hash__方法,并且其哈希值在其生命周期内始终不变。

由于我完全忽略的原因,Python列表不可散列,我想知道以下实现是否可行,或者是否存在我不知道的故障。

class L(list):
    def __hash__(self):
        return id(self)

 a = range(10)
 l = L(range(10))
 print a
 >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 print l
 >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 hash(l)
 >> 41889288
 hash(a) # unsurprisingly it returns an error because a list is not hashable
 >> Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unhashable type: 'list'

 # lets append a value to l
 l.append(1000)
 print l
 >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000]
 isinstance(l, list) # to double check whether l is a List instance
 >> True
 D = {}
 D[l] = "this is a dict with a list as key"
 print D
 {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000]: 'this is a dict with a list as key'}
 # lets append another value to l
 l.append(-10)
 print D
 >> {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000, -10]: 'this is a dict with a list as key'}

 # now lets add a normal list to the dict to the dict
 D[a] = "Add a list as key"
 >>Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   TypeError: unhashable type: 'list'

所以这是一个可哈希列表实现,几乎没有问题,我不明白为什么列表即使在可变的情况下也不能在正常的Python发行版中进行哈希处理。

NB:这个问题不是关于为什么列表不能用作字典键的问题有任何解释吗?

python python-2.7 mutable hashable
2个回答
7
投票

您有__hash__方法。它返回一些东西。它返回有用的东西吗?让我们看看。


0
投票

您可以-在有限制的情况下-使用JSON转储来比较按内容划分的质量。一个限制是,这仅适用于任何JSON可序列化的数据。

© www.soinside.com 2019 - 2024. All rights reserved.