【发布时间】:2015-01-14 19:29:24
【问题描述】:
例如:
d = {"John": "Doe", "Paul": "Allen", "Bill": "Gates"}
想象一下,这有几千/百万个这样的名字,所有名字都是唯一的。
如果我想查看密钥“Paul”是否存在,它在幕后做了什么?
【问题讨论】:
-
python 字典是hashmaps
标签: python dictionary
例如:
d = {"John": "Doe", "Paul": "Allen", "Bill": "Gates"}
想象一下,这有几千/百万个这样的名字,所有名字都是唯一的。
如果我想查看密钥“Paul”是否存在,它在幕后做了什么?
【问题讨论】:
标签: python dictionary
Python 的字典实现通过要求键对象提供“哈希”函数将字典查找的平均复杂度降低到 O(1)。这样的散列函数获取关键对象中的信息并使用它来生成一个整数,称为散列值。然后使用这个哈希值来确定这个(键,值)对应该放在哪个“桶”中。此查找函数的伪代码可能类似于:
def lookup(d, key):
'''dictionary lookup is done in three steps:
1. A hash value of the key is computed using a hash function.
2. The hash value addresses a location in d.data which is
supposed to be an array of "buckets" or "collision lists"
which contain the (key,value) pairs.
3. The collision list addressed by the hash value is searched
sequentially until a pair is found with pair[0] == key. The
return value of the lookup is then pair[1].
'''
h = hash(key) # step 1
cl = d.data[h] # step 2
for pair in cl: # step 3
if key == pair[0]:
return pair[1]
else:
raise KeyError, "Key %s not found." % key
【讨论】:
Python 字典是用哈希表实现的。所以平均 O(1) 查找(取决于散列函数的强度)。
参考资料:
【讨论】: