Python的hash函数

hash函数是一种从大集合到小集合的映射,一个对象的哈希值一般代表着它的存储位置。
可是,为什么某些对象(如字符"a")调用hash函数得到的哈希值很大很大呢

阅读 4.7k
1 个回答

先看定义:

hash(object)
    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).

hash()id()相关,id(obj)即取得对象的内存地址,所以这个数字的大小每次运行都不一样,但是对于内置类型:

print(id(int) / hash(int))  # 16.0
print(id(str) / hash(str))  # 16.0
print(id(list) / hash(list))  # 16.0

PS: 提到id还有个有趣的小整数对象池的概念:

# [-5, 256]

print(id(3) - id(2), hash(3) - hash(2))  # 32 1
print(id(45) - id(44), hash(45) - hash(44))  # 32 1
print(id(1001) - id(1000), hash(1001) - hash(1000)) # ? 1
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题