List unhashable, but tuple hashable?

前端 未结 6 862
渐次进展
渐次进展 2020-12-08 10:15

In How to hash lists? I was told that I should convert to a tuple first, e.g. [1,2,3,4,5] to (1,2,3,4,5).

So the first cannot be hashed, bu

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-08 10:42

    You could totally make that work, but I bet you wouldn't like the effects.

    from functools import reduce
    from operator import xor
    
    class List(list):
        def __hash__(self):
            return reduce(xor, self)
    

    Now let's see what happens:

    >>> l = List([23,42,99])
    >>> hash(l)
    94
    >>> d = {l: "Hello"}
    >>> d[l]
    'Hello'
    >>> l.append(7)
    >>> d
    {[23, 42, 99, 7]: 'Hello'}
    >>> l
    [23, 42, 99, 7]
    >>> d[l]
    Traceback (most recent call last):
      File "", line 1, in 
    KeyError: [23, 42, 99, 7]
    

    edit: So I thought about this some more. You could make the above example work, if you return the list's id as its hash value:

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

    In that case, d[l] will give you 'Hello', but neither d[[23,42,99,7]] nor d[List([23,42,99,7])] will (because you're creating a new [Ll]ist.

提交回复
热议问题