Python学习笔记_字典(Dict)_遍历_不同方法_性能测试对比
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python学习笔记_字典(Dict)_遍历_不同方法_性能测试对比,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1574字,纯文字阅读大概需要3分钟。
内容图文
![Python学习笔记_字典(Dict)_遍历_不同方法_性能测试对比](/upload/InfoBanner/zyjiaocheng/1311/fac4008e2d1e4ed6bb8331baae48f477.jpg)
今天专门把python的字典各种方法对比测试了一下性能效果.
测试代码如下:
1 def dict_traverse(): 2 from time import clock 3 my_dict = {‘name‘: ‘Jim‘, ‘age‘: ‘20‘, ‘height‘: ‘180cm‘, ‘weight‘: ‘60kg‘} 4 5 t_start = clock() 6for key in my_dict: # 性能最差写法.无优化 7print‘Type01.01: %s --- %s‘ % (key, my_dict[key]) 8 t1 = clock() 910for key in my_dict: # 性能较上优,可见get()方法作了优化.11print‘Type01.02: %s --- %s‘ % (key, my_dict.get(key)) 12 t2 = clock() 1314for key in my_dict.keys(): # keys()方法也是作了优化.15print‘Type02.01: %s --- %s‘ % (key, my_dict[key]) 16 t3 = clock() 1718for key in my_dict.keys(): #19print‘Type02.02: %s --- %s‘ % (key, my_dict.get(key)) 20 t4 = clock() 2122for key, value in my_dict.items(): # 标准写法,性能最佳写法23print‘Type03: %s --- %s‘ % (key, value) 24 t5 = clock() 2526for key, value in my_dict.iteritems(): # 性能较上,有少量损失.27print‘Type04: %s --- %s‘ % (key, value) 28 t6 = clock() 2930for key, value in zip(my_dict.iterkeys(),my_dict.itervalues()): # 性能较差.31print‘Type05: %s --- %s‘ % (key, value) 32 t7 = clock() 3334print‘********** time cost ******************‘35print‘Type01.01 -- total time : ‘, t1-t_start 36print‘Type01.02 -- total time : ‘, t2-t1 37print‘Type02.01 -- total time : ‘, t3-t2 38print‘Type02.02 -- total time : ‘, t4-t3 39print‘Type03 -- total time : ‘, t5-t4 40print‘Type04 -- total time : ‘, t6-t5 41print‘Type05 -- total time : ‘, t7-t6 42434445if__name__ == ‘__main__‘: 46 dict_traverse()
经过多次运行,可发现不同写法,耗时是有差异.
对比结果如下图所示.
综上对比可发现:
对于字典遍历,推荐如下写法,性能最优.
1 for k, v in my_dict.items(): 2print k, v
原文:http://www.cnblogs.com/selfrebuild/p/4206367.html
内容总结
以上是互联网集市为您收集整理的Python学习笔记_字典(Dict)_遍历_不同方法_性能测试对比全部内容,希望文章能够帮你解决Python学习笔记_字典(Dict)_遍历_不同方法_性能测试对比所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。