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'
输出:
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
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
iteritems()改变iter()在Python 3?上面的文档链接似乎与此答案不符。
items()一次创建所有项目并返回一个列表。iteritems()返回一个生成器-生成器是一个对象,每次next()调用它一次都会“创建”一个项目。