Python 字典是哈希表的一个例子吗? [英] Is a Python dictionary an example of a hash table?

查看:31
本文介绍了Python 字典是哈希表的一个例子吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 中的基本数据结构之一是字典,它允许记录键"以查找任何类型的值".这是作为哈希表在内部实现的吗?如果不是,那是什么?

解决方案

没错,就是哈希映射或者哈希表.您可以阅读 Tim Peters 所写的关于 python dict 实现的描述,此处.

这就是为什么你不能使用不可哈希"的东西作为字典键,比如列表:

<预><代码>>>>a = {}>>>b = ['一些','列表']>>>哈希(b)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:列表对象不可散列>>>a[b] = '一些'回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:列表对象不可散列

您可以阅读有关哈希表的更多信息检查它是如何在 python 中实现的 和 为什么它是这样实现的.

One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?

解决方案

Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here.

That's why you can't use something 'not hashable' as a dict key, like a list:

>>> a = {}
>>> b = ['some', 'list']
>>> hash(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable
>>> a[b] = 'some'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list objects are unhashable

You can read more about hash tables or check how it has been implemented in python and why it is implemented that way.

这篇关于Python 字典是哈希表的一个例子吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆