Python中字典遍历的方法以及性能

python中字典的遍历方式有多种,’items’, ‘iteritems’, ‘keys’,’iterkeys’, ‘itervalues’等方法都可以遍历字典中的键或值,下面通过各种方法来看一下遍历字典使用不同方法时的性能。代码如下:

#!/usr/bin/env python

from time import clock

lst = [(x, x) for x in xrange(10000000)]
dic = dict(lst)

def method1():
    start_time = clock()
    for i in dic :
        t = i + dic[i]
    end_time = clock()
    print "method 1 costs time is : " , str(end_time - start_time)

def method2():
    start_time = clock()
    for k, v in dic.items() :
        t = k + v
    end_time = clock()
    print "method 2 costs time is : " , str(end_time - start_time)

def method3():
    start_time = clock()
    for k, v in dic.iteritems() :
        t = k + v
    end_time = clock()
    print "method 3 costs time is : " , str(end_time - start_time)

def method4():
    start_time = clock()
    for k in dic.keys():
        t = k + dic[k]
    end_time = clock()
    print "method 4 costs time is : " , str(end_time - start_time)  

def method5():
    start_time = clock()
    for k in dic.iterkeys():
        t = k + dic[k]
    end_time = clock()
    print "method 5 costs time is : " , str(end_time - start_time)  

def method6():
    start_time = clock()
    for k, v in zip(dic.iterkeys(), dic.itervalues()) :
        t = k + v
    end_time = clock()
    print "method 6 costs time is : " , str(end_time - start_time)

if __name__ == '__main__' : method1(), method2(), method3(),method4(),method5(),method6()

第一次执行 Python dict_test.py的时间如下:

method 1 costs time is :  0.655
method 2 costs time is :  5.226
method 3 costs time is :  0.64
method 4 costs time is :  0.687
method 5 costs time is :  0.624
method 6 costs time is :  2.028

第二次执行 Python dict_test.py的时间如下:

method 1 costs time is :  0.639
method 2 costs time is :  5.335
method 3 costs time is :  0.64
method 4 costs time is :  0.687
method 5 costs time is :  0.639
method 6 costs time is :  2.027

第三次执行 Python dict_test.py的时间如下:

method 1 costs time is :  0.64
method 2 costs time is :  5.336
method 3 costs time is :  0.64
method 4 costs time is :  0.702
method 5 costs time is :  0.655
method 6 costs time is :  2.027

第四次执行 Python dict_test.py的时间如下:

method 1 costs time is :  0.655
method 2 costs time is :  5.475
method 3 costs time is :  0.671
method 4 costs time is :  0.687
method 5 costs time is :  0.655
method 6 costs time is :  2.027

第五次执行 Python dict_test.py的时间如下:

method 1 costs time is :  0.64
method 2 costs time is :  5.335
method 3 costs time is :  0.64
method 4 costs time is :  0.702
method 5 costs time is :  0.624
method 6 costs time is :  2.028

从数据看第1、3、5种遍历字典的方法在时间上相近,第4种遍历方法时间上跟上述三种方法相差不大,性能最差的是第二种方法,第6中方法次之。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值