Python2 中的 dict.items() 和 dict.iteritems() 有什么区别? [英] What is the difference between dict.items() and dict.iteritems() in Python2?

查看:32
本文介绍了Python2 中的 dict.items() 和 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():在字典的(键,值)对上返回一个迭代器.

dict.iteritems(): Return an iterator over the dictionary’s (key, value) pairs.

如果我运行下面的代码,每个代码似乎都返回对同一个对象的引用.是否有任何我遗漏的细微差别?

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 '	they are the same object' 
   else: print '	they are different'

print 'd.iteritems():'   
for k,v in d.iteritems():
   if d[k] is v: print '	they are the same object' 
   else: print '	they 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() 的迭代器-生成器方法.原始版本保留为向后兼容.

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() 现在返回视图,并且永远不会完全构建 list.iteritems() 方法也没有了,因为 Python 3 中的 items() 与 Python 2.7 中的 viewitems() 类似.

One of Python 3’s changes is that items() now return views, 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.

这篇关于Python2 中的 dict.items() 和 dict.iteritems() 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆