Python中哈希结构有哪几种?
python中哈希结构有哪几种?
在对哈希结构的讨论上,我们对于已经在数组中有所使用,简单的来说就是通过下标定位某一种数据的方法。那么,我们学习的一些python知识点,也会体现出一些哈希结构。本篇所要讲的是字典和集合这两种,关于具体的哈希结构会就这两个方面分别展开介绍,大季家一起来看看内容。
1、字典
PyDictKeysObject定义了字典哈希表的一些字段。其中有两个数组dk_indices[]和dk_entries[],这两个便是真正的存储数据的数组。kv数据保存在dk_entries[]数组中,dk_indices[]来存储kv数据在dk_enties数组中保存的索引。其中每个kv数据以entry的数据结构来存储,如下:
typedefstruct{
/*Cachedhashcodeofme_key.*/
Py_hash_tme_hash;
PyObject*me_key;
PyObject*me_value;/*Thisfieldisonlymeaningfulforcombinedtables*/
}PyDictKeyEntry;
me_hash缓存存key的哈希值,防止哈希值的重复计算。me_key和me_value便是key和value的真正数据了。
2、集合
集合和字典一样,底层也是哈希结构,和字典相比,可理解为只有key,没有values。
相比字典,集合简单了不少。在PySetObject中直接保存了存储数据的数组。
根据集合的底层数据结构分析,它解决哈希冲突也是使用的「开发寻址法」。
集合的一些常用操作:
#初始化
s1={'1','2','3'}#不推荐,当元素中有字典时,会报错
s2=set(['1','4','5'])
print(s1)#{'3','1','2'}
print(s2)#{'3','1','2'}
#交集
print(s1&s2)#{'1'}
#并集
print(s1|s2)#{'3','5','4','2','1'}
#差集
print(s1-s2)#{'3','2'}
#判断子集和超集
s2.issubset(s1)#s2是否为s1的子集
s1.issuperset(s2)#s1是否为s2的超集
#集合的一些内建方法
#set.add(obj)添加集合元素
#set.remove(obj)删除集合元素
#set.update(set)合并集合
#set.pop()随机删除一个元素,并返回该元素
以上就是Python中哈希结构的两种讲解,对于字典和集合的学习,大家可以结合哈希结构的内容进行深入探索,学会后可以就代码部分进行练习。更多Python学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15
pythontry语句的执行原理
pythontry语句的执行原理1、原理分析(1)执行try子句(try和except关键字之间的多行语句)。(2)如果没有异常发生,则跳过except子句并完成try语句...详情>>
2023-11-14 09:37:35热门推荐
技术干货






