Python中的列表或字典是否更快? [英] Is a list or dictionary faster in Python?

查看:140
本文介绍了Python中的列表或字典是否更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



How much of a difference are these two as far as performance?

tmp = []
tmp.append(True)
print tmp[0]

And

tmp = {}
tmp[0] = True
print tmp[0]


推荐答案

标准库中的 timeit 设计只是为了回答这样的问题!忘记 print (这会对您的终端产生不利的副作用;-)并比较:

The timeit module in the standard library is designed just to answer such questions! Forget the print (which would have the nasty side effect of spewing stuff to your terminal;-) and compare:

$ python -mtimeit 'tmp=[]; tmp.append(True); x=tmp[0]'
1000000 loops, best of 3: 0.716 usec per loop
$ python -mtimeit 'tmp={}; tmp[0]=True; x=tmp[0]'
1000000 loops, best of 3: 0.515 usec per loop

所以,dict是赢家 - 0.2微秒...! - )

So, the dict is the winner -- by 0.2 microseconds...!-)

这篇关于Python中的列表或字典是否更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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