Python 字典是如何解决哈希冲突的

2021-07-29  本文已影响0人  kingron

本文主要翻译自 so 上面的问题 Why can a Python dict have multiple keys with the same hash? Praveen Gollakota 的答案

实际测试效果如下:

class HashTester(object):
    
    def __init__(self):
        self.value = 42

    def __hash__(self):
        return self.value

    def __eq__(self, other):
        return self.value == other.value
    

class HashTester2(object):

    def __hash__(self):
        return 42
>>> a = HashTester()
>>> b = HashTester()
>>> {a: 'this is a', b: 'this is b'}  # a 与 b 的 hash 和 key 都相等
{<__main__.HashTester object at 0x00000222B7A691C0>: 'this is b'}

>>> e = HashTester2()
>>> f = HashTester2()
>>> {e: 'this is e', f: 'this is f'}  # e 与 f 哈希冲突
{<__main__.HashTester2 object at 0x00000222B7A69CD0>: 'this is e', <__main__.HashTester2 object at 0x00000222B7A690A0>: 'this is f'}
上一篇 下一篇

猜你喜欢

热点阅读