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中方法次之。