Python中的哈希元组在不同的系统中导致不同的结果 [英] Hashing tuple in Python causing different results in different systems
问题描述
num = int(raw_input())
num_list = [int(x)for x在raw_input()。split()]
print(hash(tuple(num_list)))
上面的代码导致
>>> 2
>>> 1 2
>>> 3713081631934410656
但是在我使用Python 3.4的本地PC中,答案是
>>> 1299869600
代码被接受,但我找不到导致不同结果的原因。这是针对不同版本的Python吗?
hash()
可能会在不同的操作系统,体系结构,Python实现和Python版本中为同一对象返回不同的值。
它仅用于一个Python会话中,会话或机器。所以你不应该依赖 hash()
超过这个值。
如果你需要散列相同的结果无处不在,请考虑校验和,如:
- MD5或SHA1,
- xxHash作者在多种操作系统和体系结构中提供了稳定的结果,无论是小端还是大端,32/64位,posix与否等)。 不同架构上的不同结果。例如,当我将C Murmur2移植到IBM S390 Linux安装(所有奇怪的地方!)时,我经历了这一拳头。为了避免出现问题,我终于在该OS上编写了一个缓慢而独立于脚本的纯Python实现,而不是C实现。
I was practicing tuple hashing. In there I was working on Python 2.7. Below is the code:
num = int(raw_input())
num_list = [int(x) for x in raw_input().split()]
print(hash(tuple(num_list)))
The above code results in
>>> 2
>>> 1 2
>>> 3713081631934410656
But at my local PC where I am using Python 3.4 the answer is
>>> 1299869600
The code is accepted but I could not find out what causes the different results. Is this for different version of Python?
The hash()
may return different values for the same object on different OS, architectures, Python implementations and Python versions.
It is designed to be used only within a single Python session, not across sessions or machines. So you should never rely on the value of hash()
beyond this.
If you need hashing that yields the same results everywhere, consider checksums such as:
- MD5 or SHA1,
- xxHash which per its author provides stable results across multiple OS and architecture, be it little or big endian, 32/64 bits, posix or not, etc.)
- or with some caution Murmur as some versions may yield different results on different architectures. For instance I experienced this fist hand when porting a C Murmur2 to an IBM S390 Linux install (of all odd places!). To avoid issues I ended instead coding a slow but arch-independent pure Python implementation on that OS rather than a C implementation.
这篇关于Python中的哈希元组在不同的系统中导致不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!