python - 元组上的哈希输出不一致

标签 python hash tuples python-3.7

比较 hash es 用于一些二元组

for i in range(11):
    print(i, hash((i,i)) == hash((-i,-i)))

我希望在 i==0 时得到 True,在其余情况下得到 False。我很惊讶地看到这个:

0 True
1 False
2 True
3 True
4 True
5 True
6 True
7 True
8 False
9 True
10 True

为什么会这样?

据我所知,这与 this 中的问题不同问题,因为这与顺序无关,而与值(value)观本身有关。

最佳答案

散列值永远无法保证无冲突,即使优秀的散列算法努力做到这一点。 Python 3.8 改进了哈希算法,特别是针对元组的哈希算法,因此与 Python 3.7 相比,问题中的问题现在变得更难在 Python 3.8 中重现。

摘自 changelog for Python 3.8.0 alpha 1 :

bpo-34751: The hash function for tuples is now based on xxHash which gives better collision results on (formerly) pathological cases. Additionally, on 64-bit systems it improves tuple hashes in general. Patch by Jeroen Demeyer with substantial contributions by Tim Peters.

关于python - 元组上的哈希输出不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61275518/

相关文章:

Python - 如何为许多类似结构的函数创建通用批处理函数

python - Django 无法打开表中的数据库

python - python web.py模块中的web.session.Session是什么

c++ - 如何创建具有 64 位输出的良好 hash_combine(受 boost::hash_combine 启发)

Java直接引用哈希值

haskell - 如何从 Haskell 中的 10 元组中获取第 n 个元素?

python - 如何将元组作为函数的参数传递

python - 分类结果取决于random_state?

ruby-on-rails - Ruby Looking Array of hash 性能

python - 遍历元组并计算数字的百分比