Python数据结构教程:散列(哈希表)

2018-10-1610:46:29数据结构与算法Comments2,740 views字数 1334阅读模式

散列表(也叫哈希表)是一种数据结构,其数据元素的地址或索引值由散列函数生成。 这使得访问数据的速度更快,因为索引值是数据值的关键字。 换句话说,哈希表存储键值对,但键是通过哈希函数生成的。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

因此,数据元素的搜索和插入函数变得更快,因为键值本身成为存储数据的数组的索引。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

Python中,字典数据类型表示哈希表的实现。字典中的键满足以下要求。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

  • 字典的键是可散列的,即通过散列函数生成该散列函数,该散列函数为提供给散列函数的每个唯一值生成唯一结果。
  • 字典中数据元素的顺序不固定。

所以可通过使用下面的字典数据类型来看到哈希表的实现。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

在字典中访问值

要访问字典元素,可以使用熟悉的方括号 - [] 来获取它的值。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

# Declare a dictionary 
dict = {'Name': 'maxsu', 'Age': 27, 'Class': 'First'}

# Accessing the dictionary with its key
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

dict['Name']:  maxsu
dict['Age']:  27
Shell

更新字典元素

可以通过添加新条目或键值对,修改现有条目或删除现有条目来更新字典,如简单示例中所示 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

# Declare a dictionary
dict = {'Name': 'Maxsu', 'Age': 26, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "第一中学"; # Add new entry
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Python

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

dict['Age']:  8
dict['School']:  第一中学
Shell

删除字典元素

可以删除单个字典元素,也可以清除字典的全部内容。 也可以在一个操作中删除整个字典。 要显式删除整个字典,只需使用del语句。 参考以下代码 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html


dict = {'Name': 'Maxsu', 'Age': 26, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear();     # remove all entries in dict
del dict ;        # delete entire dictionary

print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
Python

执行上面示例代码,得到以下结果 -文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

请注意,由于在执行del语句之后,字典不再存在之后会引发异常。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html

Traceback (most recent call last):
  File "F:\worksp\pythonds\test.py", line 7, in <module>
    print ("dict['Age']: ", dict['Age'])
TypeError: 'type' object is not subscriptable
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/suanfa/6786.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/suanfa/6786.html

Comment

匿名网友 填写信息

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

确定