张祎

导航

python 中 五种字典(dict)的遍历方法,实验法比较性能。

1 、背景:

      想知道5种遍历方法,并且知道从性能角度考虑,使用哪种。

2、结论:

    使用这种方式:

    for key,val in AutoDict.iteritems():
        temp = "%s:%s" % (key,val)

  不用这种方式:

    for (key,val) in AutoDict.items():
        temp = "%s:%s" % (key,val)

 实验:

import time
def testDict():
    count = 1000000
    AutoDict = {}
    for i in xrange(count):
        AutoDict[i] = i    
    startTime = time.time()
    for d in AutoDict:
        temp = "%s:%s" % (d,AutoDict[d])
    #method 1  
    print 'span time 1 :%s' % str(time.time()-startTime)
    startTime = time.time()
    for (key,val) in AutoDict.items():
        temp = "%s:%s" % (key,val)
    #method 2
    print 'span time 2 :%s' % str(time.time()-startTime)
    startTime = time.time()
    for key,val in AutoDict.iteritems():
        temp = "%s:%s" % (key,val)
    #method 3
    print 'span time 3 :%s' %str(time.time()-startTime)
    startTime = time.time()
    for key in AutoDict.iterkeys():
        temp = "%s:%s" %(key,AutoDict[key])
    #method 4
    print 'span time 4 :%s' %str(time.time()-startTime)
    startTime = time.time()
    for key,val in zip(AutoDict.iterkeys(),AutoDict.itervalues()):
        temp = "%s:%s" %(key,val)
    #method 5
    print 'span time 5 :%s' %str(time.time()-startTime)

testDict()

多次实验的平均值:

span time 1 :0.206
span time 2 :0.508
span time 3 :0.195
span time 4 :0.205
span time 5 :0.307

 

posted on 2016-01-19 20:44  张祎  阅读(845)  评论(0编辑  收藏  举报