Hash tables are supposed be high-performance mappings , and because Python dicts are implemented with hash tables ,它们的性能也很高。但是我在查看负整数的哈希值时遇到了一个奇怪的结果。
>>> for i in range(7):
... print hash(i-4)
...
-4
-3
-2
-2
0
1
2
但这显然对字典没有影响:
>>> d = dict()
>>> d[-1] = 'foo'
>>> d[-2] = 'bar'
>>> d
{-2: 'bar', -1: 'foo'}
为什么会发生这种情况,为什么在我使用听写时不受影响?
最佳答案
x
与 y
具有不同的哈希值这一事实意味着 x != y
。但反过来就不是这样了!因此,当 x
的散列值等于 y
时,它们仍然会被显式检查是否相等。
hash(x) == hash(y)
和 x != y
的情况在哈希函数,这是很可能不时发生的事情。你想尽可能避免它,但总的来说这是不可避免的。您可以阅读更多关于哈希函数和冲突的信息 here .
关于python - 为什么 CPython Dicts 不受负一和负二哈希值的影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20156022/