gpt4 book ai didi

python - 为什么 CPython 的 hash(-1) != -1

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:04 24 4
gpt4 key购买 nike

int.__hash__ 简单地返回值似乎是合理的。果然,这似乎是 CPython 实现它的方式:

>>> hash(1)
1
>>> hash(2)
2
>>> hash(123456789)
123456789
>>> hash(-123456789)
-123456789

好的,那么这是否适用于所有 大部分整数 x?

>>> [x for x in range(-10000, 10000) if hash(x) != x]
[-1]

嗯?

>>> hash(-1)
-2

为什么 -1 是这个规则的异常(exception)?

最佳答案

来自 http://effbot.org/zone/python-hash.htm :

The hash value -1 is reserved (it’s used to flag errors in the C implementation). If the hash algorithm generates this value, we simply use -2 instead.

关于python - 为什么 CPython 的 hash(-1) != -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16872242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com