python hash()函数,转换哈希值

hash()函数

该函数是python内置的函数,可以用于将python的对象转换为hash值,即哈希值。

语法

hash(obj, /)

python源码中对hash()函数的介绍:

    Return the hash value for the given object.
    
    Two objects that compare equal must also have the same hash value, but the
    reverse is not necessarily true.

参数

参数描述
objpython对象,如浮点数float、元组tuple、字符串str等,dict字典、列表list和set集合不能作为参数传递。
>>> hash([1,2]) #参数为list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash((1,)) #参数为tuple
3430019387558
>>> hash((1,2))
3713081631934410656
>>> hash({3,5}) #参数为set
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> hash({'a':1,'b':2}) #参数为dict
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> hash(1.05) #参数为float
115292150460684801
>>> hash('a')
-3509364219097915192
>>> hash('abc') #参数为str
1076320974621744098

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.