【发布时间】:2012-05-14 13:33:57
【问题描述】:
dict.items() 和 dict.iteritems() 之间有什么适用的区别吗?
来自Python docs:
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'
输出:
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
【问题讨论】:
-
它们的计算方式基本上有所不同。
items()一次创建所有项目并返回一个列表。iteritems()返回一个生成器 - 生成器是一个对象,每次在其上调用next()时,它一次“创建”一个项目。 -
在您的特定情况下,
d[k] is v将始终返回 True,因为 python 为 -5 到 256 之间的所有整数保留一个整数对象数组:docs.python.org/2/c-api/int.html 当您在该范围内创建一个 int 时,您实际上只需取回对现有对象的引用:>> a = 2; b = 2 >> a is b True但是,>> a = 1234567890; b = 1234567890 >> a is b False -
@the_wolf 我认为最好添加您在问题中引用的文档的 python 版本。
-
在 Python 3 中
iteritems()是否更改为iter()?上面的文档链接似乎与这个答案不匹配。 -
不完全是,@GabrielStaples。 iteritems() 从字典 Python 3 中删除,并且没有替代品。然而,为了同样的效果,你确实使用了 iter()。例如迭代(dict.items())。见鼓舞士气 469:python.org/dev/peps/pep-0469
标签: python dictionary python-2.x