字符串上的 Python hash() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40298023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:22:34  来源:igfitidea点击:

Python hash() function on strings

pythonhash

提问by d-d

How does a hash value of some particular string is calculated in CPython2.7?

在 CPython2.7 中如何计算某个特定字符串的哈希值?

For instance, this code:

例如,这段代码:

print hash('abcde' * 1000)

returns the same value even after I restart the Python process and try again (I did it many times).

即使在我重新启动 Python 进程并重试后,也返回相同的值(我做了很多次)。

So, it seems that id()(memory address) of the string doesn't used in this computation, right? Then how?

所以,id()在这个计算中似乎没有使用字符串的(内存地址),对吗?那怎么办?

回答by Selcuk

Hash values are not dependent on the memory location but the contents of the object itself. From the documentation:

哈希值不依赖于内存位置,而是依赖于对象本身的内容。从文档

Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).

返回对象的哈希值(如果有)。哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数值具有相同的哈希值(即使它们属于不同类型,如 1 和 1.0 的情况)。

You can check out the source code for CPython implementation of the hashmethod of strclass here:

您可以在此处查看类hash方法的CPython 实现的源代码str

https://svn.python.org/projects/python/trunk/Objects/stringobject.c

https://svn.python.org/projects/python/trunk/Objects/stringobject.c