python dict遍历文件_python 字典(dict)遍历的四种方法性能测试报告

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

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

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

python test.py0.00184039735833 0.00326492977712 0.00214993552657 0.00311549755797python test.py0.00182356570728 0.00339342506446 0.00234863111466 0.00321566640817python test.py0.00185107108827 0.00324563495762 0.00211175641563 0.00313479237748python test.py0.0018215130669 0.00320950848705 0.00215814608806 0.00322798225041python test.py0.00216635664955 0.00391807994377 0.00207604047314 0.00322757172233

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值