列表可变和可清除

Cob*_*bry 0 python mutable python-2.7 hashable

可散列的对象需要一个__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'
Run Code Online (Sandbox Code Playgroud)

所以这个可清除列表实现几乎没有问题,我不明白为什么列表不能在普通的Python发行版中可以清除,即使它仍然是可变的.

注意:这个问题不是关于为什么列表不能用作字典键的原因任何解释?

use*_*ica 7

你有一个__hash__方法.它返回一些东西.它会返回有用的东西吗?让我们来看看.

>>> a = L([1, 2])
>>> b = L([1, 2])
>>> a == b
True
>>> s = set([a, b])
>>> s
set([[1, 2], [1, 2]])
Run Code Online (Sandbox Code Playgroud)

不!它打破了任何使用代码所做的假设hash,特别是相等的对象具有相等的哈希值.现在我们有一个包含两个相等对象的集合.您可以通过排序的解决这个问题==,并!=通过身份比较,虽然那么你也失去订单总额必须删除<,>,<=,和>=.这是很多有用的东西,你必须拿出来使列表有意义地清洗.

  • @Cobry:此外,不假设相等的对象具有相同的ID.假设对于任何对象`a`和`b`,`a == b`意味着`hash(a)== hash(b)`.这个属性是哈希的整个点,也是它们有用的全部原因; 你的`__hash__`没有这个属性. (2认同)