Python遍历字典的四种方法对比
生活随笔
收集整理的這篇文章主要介紹了
Python遍历字典的四种方法对比
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
#!/usr/bin/python
from time import clockl = [(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 = vt2 = 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遍历字典的四种方法对比的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python函数参数传递:传值还是传引用
- 下一篇: Python 学习笔记 多进程 mult