Python hash() 函数用法

2023-09-17 22:27:54

hash() 方法返回指定对象的哈希值。哈希值用于数据存储,并在每次检索的短时间内访问数据,存储空间仅略大于数据或记录本身所需的总空间。在 Python 中,具有值用于比较字典键以访问值。

语法:

hash(object)

参数:

对象:必需。要返回其哈希值的对象(整数、字符串、浮点数)。

返回类型:

返回一个整数(对象的哈希值)

下面的示例演示 hash() 方法。

print("The hash value of 200 is: ", hash(200))
print("The hash value of 200.01 is: ", hash(200.01))
print("The hash value of programming is: ", hash("programming"))
print("The hash value for a tuple is: ", hash((1,2,3,4,5)))

输出:

The hash value of 200 is:  200
The hash value of 200.01 is:  23058430092116168
The hash value of programming is:  -857083564838631708
The hash value for a tuple is:  8315274433719620810

如果一个对象被传递为参数是不可哈希的,例如列表对象,那么TypeError异常就会被抛出。

print(hash([1,2,3,4])

输出:

Traceback (most recent call last):
    print(hash([1,2,3,4]))
TypeError: unhashable type: 'list'