问题描述
我相信 hash()
函数在所有 python 解释器中的工作原理都是一样的.但是当我使用 python for android 在我的手机上运行它时它会有所不同.我对散列字符串和数字得到相同的散列值,但是当我散列内置数据类型时,散列值不同.
PC Python 解释器 (Python 2.7.3)
>>>哈希(整数)31585118>>>哈希(你好 sl4a")1532079858>>>哈希(101)101移动 Python 解释器 (Python 2.6.2)
>>>哈希(整数)-2146549248>>>哈希(你好 sl4a")1532079858>>>哈希(101)101谁能告诉我这是一个错误还是我误解了什么.
对于旧的python(至少,我的Python 2.7),似乎
hash() = id()/16
对于 CPython id()
是内存中的地址 - http://docs.python.org/2/library/functions.html#id
所以我的猜测是 Android 端口对内存地址有一些奇怪的约定?
无论如何,鉴于上述情况,类型(以及我猜的其他内置函数)的哈希值会因安装而异,因为函数位于不同的地址.
相比之下,值的散列(我认为您所说的非内部对象"是指非内部对象")(在添加随机内容之前)是根据它们的值计算的,因此很可能是可重复的.
PS 但至少还有一个 CPython 问题:
>>>对于 i 在范围内(-1000,1000):...如果 hash(i) != i: 打印(i)...-1这里有一个答案解释了那个...
I believed that hash()
function works the same in all python interpreters. But it differs when I run it on my mobile using python for android. I get same hash value for hashing strings and numbers but when I hash built-in data types the hash value differs.
PC Python Interpreter (Python 2.7.3)
>>> hash(int)
31585118
>>> hash("hello sl4a")
1532079858
>>> hash(101)
101
Mobile Python Interpreter (Python 2.6.2)
>>> hash(int)
-2146549248
>>> hash("hello sl4a")
1532079858
>>> hash(101)
101
Can any one tell me is it a bug or I misunderstood something.
for old python (at least, my Python 2.7), it seems that
hash(<some type>) = id(<type>) / 16
and for CPython id()
is the address in memory - http://docs.python.org/2/library/functions.html#id
>>> id(int) / hash(int)
16
>>> id(int) % hash(int)
0
so my guess is that the Android port has some strange convention for memory addresses?
anyway, given the above, hashes for types (and other built-ins i guess) will differ across installs because functions are at different addresses.
in contrast, hashes for values (what i think you mean by "non-internal objects") (before the random stuff was added) are calculated from their values and so likely repeatable.
PS but there's at least one more CPython wrinkle:
>>> for i in range(-1000,1000):
... if hash(i) != i: print(i)
...
-1
there's an answer here somewhere explaining that one...
这篇关于为什么 Python 哈希函数在 Android 实现上运行时不会给出相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!