python中的字典的效率非常高,比列表的查找更高效,而且数据结构规模越大,差距越明显。
我们看下面这个例子:
我们需要找到男孩列表和女孩列表里首字母相同的配对。
首先我们看列表的情况:
import time
if __name__=="__main__":
girls = ['java','daodao','jingjing','tudou','dandan','baobao']
boys = ['yuanyuan','dada','jiji','chuichui','shuaige','baichi']
starttime = time.time()
print [b+'+'+g for b in boys for g in girls if b[0]==g[0]]
cost = time.time() - starttime
print cost
Result:
['dada+daodao', 'dada+dandan', 'jiji+java', 'jiji+jingjing', 'baichi+baobao']
3.09944152832e-05
我们再看看字典的情况:
import time
if __name__=="__main__":
girls = ['java','daodao','jingjing','tudou','dandan','baobao']
boys = ['yuanyuan','dada','jiji','chuichui','shuaige','baichi']
lettergirls = {}
for girl in girls:
lettergirls.setdefault(girl[0],[]).append(girl)
starttime = time.time()
print [b+'+'+g for b in boys for g in lettergirls.get(b[0],[])]
cost = time.time()-starttime
print cost
Result:
['dada+daodao', 'dada+dandan', 'jiji+java', 'jiji+jingjing', 'baichi+baobao']
2.47955322266e-05
输出相同的结果,但是很明显字典耗时更少,更高效。