Python 字典是哈希表的一个例子吗? [英] Is a Python dictionary an example of a hash table?
问题描述
Python 中的基本数据结构之一是字典,它允许记录键"以查找任何类型的值".这是作为哈希表在内部实现的吗?如果不是,那是什么?
没错,就是哈希映射或者哈希表.您可以阅读 Tim Peters 所写的关于 python dict 实现的描述,此处.
这就是为什么你不能使用不可哈希"的东西作为字典键,比如列表:
<预><代码>>>>a = {}>>>b = ['一些','列表']>>>哈希(b)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:列表对象不可散列>>>a[b] = '一些'回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:列表对象不可散列您可以阅读有关哈希表的更多信息 或
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屋!