您的位置:首页 > 编程语言 > Python开发

Python遍历字典的四种方法对比

2015-05-13 23:56 633 查看
#!/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():
...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: