例如:
d = {"John": "Doe", "Paul": "Allen", "Bill": "Gates"}
只有想象这有几千个这样的名字,所有名字都是唯一的。
如果我想看看关键字“保罗”是否存在,它会在引擎盖下做什么?
答案 0 :(得分:4)
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
答案 1 :(得分:2)