某些dict.items()是Python中的迭代器吗?
我对迭代器和iterables之间的区别有点困惑。我读了很多书,得到了很多: 迭代器:在其类中包含某些dict.items()是Python中的迭代器吗?,python,python-3.x,dictionary,iterator,iterable,Python,Python 3.x,Dictionary,Iterator,Iterable,我对迭代器和iterables之间的区别有点困惑。我读了很多书,得到了很多: 迭代器:在其类中包含\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu的对象。可以对其调用next()。所有迭代器都是可迭代的 Iterable:在其类中定义\uuuu iter\uuuuu或\uuuu getitem\uuuuuu的对象。如果可以使用iter()构建迭代器,那么某些东西是可移植的。并非所有的iterable都是迭代器 某些dict.
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
的对象。可以对其调用next()。所有迭代器都是可迭代的
Iterable:在其类中定义\uuuu iter\uuuuu
或\uuuu getitem\uuuuuu
的对象。如果可以使用iter()构建迭代器,那么某些东西是可移植的。并非所有的iterable都是迭代器
某些dict.items()是迭代器吗?我知道一些dict.iteritems()
会在Python2中,对吗
我只是检查,因为我正在做的一门课程说它是,我很确定它只是一个iterable(不是迭代器)
感谢您的帮助:)您可以直接测试:
from collections import Iterator, Iterable
a = {}
print(isinstance(a, Iterator)) # -> False
print(isinstance(a, Iterable)) # -> True
print(isinstance(a.items(), Iterator)) # -> False
print(isinstance(a.items(), Iterable)) # -> True
不,不是。这是一个目录中项目的可编辑视图:
>>> next({}.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict_items' object is not an iterator
>>>
请自己检查一下:
d = {'a': 1, 'b': 2}
it = d.items()
print(next(it))
这会导致类型错误:“dict_items”对象不是迭代器
另一方面,您可以始终迭代d.items()
,如下所示:
d = {'a': 1, 'b': 2}
for k, v in d.items():
print(k, v)
或:
dict.items
根据以下条件返回a:
可能重复的@ytu实际上不是重复的IMO,而且无论如何,接受的答案不正确地描述了这一个的细节。@juanpa.arrivillaga我知道接受的答案是不正确的。这里的讨论仍然涵盖了很多内容,足以解决这个问题。@zvone但是您不能对
项调用next()
,所以它的行为肯定不像迭代器?关于重复问题,我以前读过这个答案,但我觉得它可能不够简单,我无法理解:P现在回顾一下,结合这里的答案,我确实明白了,所以我很高兴接受重复问题,如果这是共识的话?(对stackoverflow来说相当陌生)@E.Hazledine-是的,但我猜OP想知道它的行为是像python 2中的项
,还是像iteritems
,在这种情况下,所有正确的答案都会导致错误的结论。因此,我简化了我的评论
d = {'a': 1, 'b': 2}
for k, v in d.items():
print(k, v)
d = {'a': 1, 'b': 2}
it = iter(d.items())
print(next(it)) # ('a', 1)
print(next(it)) # ('b', 2)
In [5]: d = {1: 2}
In [6]: next(d.items())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-945b6258a834> in <module>()
----> 1 next(d.items())
TypeError: 'dict_items' object is not an iterator
In [7]: next(iter(d.items()))
Out[7]: (1, 2)
In [14]: d = {1: 2, 3: 4}
In [15]: it = iter(d.items())
In [16]: next(it)
Out[16]: (1, 2)
In [17]: d[3] = 5
In [18]: next(it)
Out[18]: (3, 5)