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(): ...
相关文章推荐
- Python遍历字典的四种方法对比
- python 字典(dict)遍历四种方法的性能
- python 字典(dict)遍历的四种方法性能测试报告
- python 字典(dict)遍历四种方法的性能
- python 字典(dict)遍历的四种方法性能测试报告
- 遍历python字典几种方法
- Python中字典(dict)合并的四种方法总结
- python字典键值对的添加和遍历方法
- python两种遍历字典(dict)的方法比较
- OpenCV图像元素遍历四种方法的源码及性能对比
- Python字典的遍历方法
- Python中使用item()方法遍历字典的例子
- Python获取当前页面内所有链接的四种方法对比分析
- Hashtable类中的四种遍历方法对比
- python两种遍历字典(dict)的方法比较
- 遍历python字典几种方法总结(推荐)
- Python中遍历字典过程中更改元素导致异常的解决方法
- python 循环遍历字典元素的简单方法
- 遍历python字典几种方法
- Python 字典的 get() 方法和 [key] 方法对比