和 之间是否有任何适用的区别?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
这是进化的一部分。
最初,Python构建了一个真实的元组列表并返回了它。这可能会占用大量额外的内存。items()
然后,生成器被引入到一般的语言中,并且该方法被重新实现为名为 的迭代器生成器方法。保留原件以向后兼容。iteritems()
Python 3 的一个变化是现在返回视图,并且永远不会完全构建。该方法也消失了,因为在Python 3中的工作方式与Python 2.7类似。items()
list
iteritems()
items()
viewitems()
dict.items()
返回 2 元组 () 的列表,而 是生成 2 元组的生成器。前者最初需要更多的空间和时间,但访问每个元素的速度很快,而第二个最初需要更少的空间和时间,但生成每个元素的时间会更多。[(key, value), (key, value), ...]
dict.iteritems()
命令,并返回字典的对、键和值列表的副本。
如果复制的列表非常大,这可能会占用大量内存。dict.items()
dict.keys()
dict.values()
(k, v)
命令,并返回字典对、键和值的迭代器。dict.iteritems()
dict.iterkeys()
dict.itervalues()
(k, v)
命令 ,并返回视图对象,这些对象可以反映字典的更改。
(即,如果您在字典中添加了一个项目或一对,则视图对象可以同时自动更改。dict.viewitems()
dict.viewkeys()
dict.viewvalues()
del
(k,v)
$ python2.7
>>> d = {'one':1, 'two':2}
>>> type(d.items())
<type 'list'>
>>> type(d.keys())
<type 'list'>
>>>
>>>
>>> type(d.iteritems())
<type 'dictionary-itemiterator'>
>>> type(d.iterkeys())
<type 'dictionary-keyiterator'>
>>>
>>>
>>> type(d.viewitems())
<type 'dict_items'>
>>> type(d.viewkeys())
<type 'dict_keys'>
在 Py3.x 中,事情更加干净,因为只有 和可用,它们像在 Py2.x 中一样返回视图对象。dict.items()
dict.keys()
dict.values()
dict.viewitems()
正如@lvc所指出的,view 对象与迭代器不同,因此如果您想在 Py3.x 中返回迭代器,可以使用:iter(dictview)
$ python3.3
>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>
模板简介:该模板名称为【Python2 中的 dict.items() 和 dict.iteritems() 有什么区别?】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【Python】栏目查找您需要的精美模板。