标签:python
#!/usr/bin/python
from time import clock
l = [(x,x) for x in xrange (10000000)]
d = dict(l)
t0 = clock()
# 方法一
for i in d:
n = d[i]
t1 = clock()
# 方法二:最慢
for k,v in d.items():
n = v
t2 = clock()
# 方法三: 最快,推荐方法
for k,v in d.iteritems():
n = v
t3 = clock()
# 方法四
for k,v in zip(d.iterkeys(),d.itervalues()):
n = v
t4 = clock()
print t1 - t0, t2 - t1, t3 - t2, t4 - t3
以上代码执行五次,结果分别为:
root@ubuntu:~# python test.py
1.892906 11.893149 1.859164 3.45618
root@ubuntu:~# python test.py
2.038906 11.808548 1.969358 3.498633
root@ubuntu:~# python test.py
2.059066 11.473983 1.96166 3.695533
root@ubuntu:~# python test.py
2.092667 11.372379 1.9519 3.656708
root@ubuntu:~# python test.py
2.082951 12.910404 2.021785 3.663504
可见,最快的方法是:
for k,v in d.iteritems():
...
标签:python
原文地址:http://blog.csdn.net/cashey1991/article/details/45704249