Python中的hash()方法怎么使用?

2021年3月18日15:26:09 发表评论 579 次浏览

在数字技术的新时代, 机器学习, 人工智能和网络安全正在崛起。 Python作为实现许多此方面的好语言而脱颖而出。

Python提供hash() 将数据编码为无法识别的值的方法。

语法:hash(obj)参数:obj:我们需要转换为哈希的对象。返回:如果可能, 返回哈希值。

代码1:演示hash()的工作

# Python 3 code to demonstrate 
# working of hash()
  
# initializing objects
int_val = 4
str_val = 'lsbin'
flt_val = 24.56
  
# Printing the hash values.
# Notice Integer value doesn't change
# You'l have answer later in article.
print ( "The integer hash value is : " + str ( hash (int_val)))
print ( "The string hash value is : " + str ( hash (str_val)))
print ( "The float hash value is : " + str ( hash (flt_val)))

输出如下:

The integer hash value is : 4
The string hash value is : -5570917502994512005
The float hash value is : 1291272085159665688

hash()的属性

  • 使用散列的对象hash()是不可逆的, 导致信息丢失。
  • hash()仅针对不可变对象返回哈希值, 因此可以用作检查可变/不可变对象的指标。

代码2:演示hash()的属性

# Python 3 code to demonstrate 
# property of hash()
  
# initializing objects
# tuple are immutable
tuple_val = ( 1 , 2 , 3 , 4 , 5 )
  
# list are mutable
list_val = [ 1 , 2 , 3 , 4 , 5 ]
  
# Printing the hash values.
# Notice exception when trying
# to convert mutable object
print ( "The tuple hash value is : " + str ( hash (tuple_val)))
print ( "The list hash value is : " + str ( hash (list_val)))

输出如下:

The tuple hash value is : 8315274433719620810

例外情况:

Traceback (most recent call last):
  File "/home/eb7e39084e3d151114ce5ed3e43babb8.py", line 15, in 
    print ("The list hash value is : " + str(hash(list_val)))
TypeError: unhashable type: 'list'

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: