dict.items()和dict.iteritems()有什么区别? [英] What is the difference between dict.items() and dict.iteritems()?
问题描述
dict.items( )
和 dict.iteritems()
?
从Python文档:
dict.items()
:返回字典的(键,值)对列表的复制。
dict.items()
: Return a copy of the dictionary’s list of (key, value) pairs.
dict.iteritems()
:返回一个迭代器值)对。
如果我运行下面的代码,每个似乎都返回对同一个对象的引用。有没有什么微妙的差异,我失踪了?
If I run the code below, each seems to return a reference to the same object. Are there any subtle differences that I am missing?
#!/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'
输出:
d.items():
they are the same object
they are the same object
they are the same object
d.iteritems():
they are the same object
they are the same object
they are the same object
推荐答案
这是进化的一部分。
最初,Python items()
构建了一个真正的元组列表,并返回。这可能需要很多额外的记忆。
Originally, Python items()
built a real list of tuples and returned that. That could potentially take a lot of extra memory.
然后,生成器一般被引入到语言中,该方法被重新实现为一个名为 iteritems()$的迭代器生成器方法C $ C>。原始版本保持向后兼容性。
Then, generators were introduced to the language in general, and that method was reimplemented as an iterator-generator method named iteritems()
. The original remains for backwards compatibility.
Python 3的更改之一是 items()
现在返回迭代器,并且一个列表从未完全构建。 iteritems()
方法也没有了,因为Python 3中的 items()
类似于 viewitems()
在Python 2.7中。
One of Python 3’s changes is that items()
now return iterators, and a list is never fully built. The iteritems()
method is also gone, since items()
in Python 3 works like viewitems()
in Python 2.7.
这篇关于dict.items()和dict.iteritems()有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!