dict.items()和之间是否有任何适用的差异dict.iteritems()?
从Python文档:
dict.items():返回字典的(键,值)对列表的副本.
dict.iteritems():在字典(键,值)对上返回一个迭代器.
如果我运行下面的代码,每个似乎都返回对同一对象的引用.我缺少哪些微妙的差异?
#!/usr/bin/python
d={1:'one',2:'two',3:'three'}
print 'd.items():'
for k,v in d.items():
if d[k] is v: print '\tthey are the same object'
else: print '\tthey are different'
print 'd.iteritems():'
for k,v in d.iteritems():
if d[k] is v: print '\tthey are the same object'
else: print '\tthey are different'
Run Code Online (Sandbox Code Playgroud)
输出:
d.items():
they are the same object
they are the same object
they are the same object
d.iteritems():
they are the same …Run Code Online (Sandbox Code Playgroud) 我使用的是带有8GB内存和1.7GHz Core i5的Python 2.7.5 @ Mac OS X 10.9.3.我测试了时间消耗如下.
d = {i:i*2 for i in xrange(10**7*3)} #WARNING: it takes time and consumes a lot of RAM
%time for k in d: k,d[k]
CPU times: user 6.22 s, sys: 10.1 ms, total: 6.23 s
Wall time: 6.23 s
%time for k,v in d.iteritems(): k, v
CPU times: user 7.67 s, sys: 27.1 ms, total: 7.7 s
Wall time: 7.69 s
Run Code Online (Sandbox Code Playgroud)
似乎iteritems更慢.我想知道iteritems比直接访问dict有什么好处.
更新:获得更准确的时间配置文件
In [23]: %timeit -n 5 for k in d: …Run Code Online (Sandbox Code Playgroud)