手机
当前位置:查字典教程网 >脚本专栏 >python >python 字典(dict)遍历的四种方法性能测试报告
python 字典(dict)遍历的四种方法性能测试报告
摘要:python中,遍历dict的方法有四种。但这四种遍历的性能如何呢?我做了如下的测试l=[(x,x)forxinxrange(10000)]...

python中,遍历dict的方法有四种。但这四种遍历的性能如何呢?我做了如下的测试

l = [(x,x) for x in xrange(10000)] d = dict(l) from time import clock t0=clock() for i in d: t = i + d[i] t1=clock() for k,v in d.items(): t = k + v t2=clock() for k,v in d.iteritems(): t = k + v t3=clock() for k,v in zip(d.iterkeys(),d.itervalues()): t = k + v t4=clock() print t1-t0, t2-t1, t3-t2, t4-t3

将这段脚本运行5次,结果如下:

python test.py 0.00184039735833 0.00326492977712 0.00214993552657 0.00311549755797 python test.py 0.00182356570728 0.00339342506446 0.00234863111466 0.00321566640817 python test.py 0.00185107108827 0.00324563495762 0.00211175641563 0.00313479237748 python test.py 0.0018215130669 0.00320950848705 0.00215814608806 0.00322798225041 python test.py 0.00216635664955 0.00391807994377 0.00207604047314 0.00322757172233

显然第一种方法效率最高,第三种方法略差一点但相差无几,方法二四性能就差得多

不过实际的差别不是太大,不必过于纠结

【python 字典(dict)遍历的四种方法性能测试报告】相关文章:

python每次处理固定个数的字符的方法总结

Python中关键字is与==的区别简述

python函数返回多个值的示例方法

Python 字典(Dictionary)操作详解

python解决字典中的值是列表问题的方法

python去掉字符串中重复字符的方法

Python 列表(List)操作方法详解

python实现问号表达式(?)的方法

Python 开发Activex组件方法

Python列表推导式的使用方法

精品推荐
分类导航