some_dict.items()是Python中的迭代器吗?

问题描述 投票:0回答:4

我对迭代器和迭代器之间的区别感到有点困惑。我做了很多阅读并且得到了这么多:

迭代器:在它的类中有__next__的对象。你可以在上面调用next()。所有迭代器都是可迭代的。

Iterable:一个在其类中定义__iter____getitem__的对象。如果可以使用iter()构建迭代器,那么它是可迭代的。并非所有迭代都是迭代器。

some_dict.items()是迭代器吗?我知道some_dict.iteritems()会在Python2中吗?

我只是检查,因为我正在做的课程说它是,我很确定它只是一个可迭代的(不是迭代器)。

谢谢你的帮助 :)

python python-3.x dictionary iterator iterable
4个回答
1
投票

不,不是。它是dict中项目的可迭代视图:

>>> next({}.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'dict_items' object is not an iterator
>>>

这是__iter__方法返回一个专门的迭代器实例:

>>> iter({}.items())
<dict_itemiterator object at 0x10478c1d8>
>>>

0
投票

您可以直接测试:

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

0
投票

根据dict.itemsdict view返回docs

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)

回答你的问题,dict.items不是一个迭代器。它是一个可迭代的对象,它支持len__contains__并反映原始字典中所做的更改:

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)

0
投票

检查一下:

d = {'a': 1, 'b': 2}

it = d.items()
print(next(it))

这导致TypeError: 'dict_items' object is not an iterator

另一方面,你总是可以通过d.items()迭代:

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)
© www.soinside.com 2019 - 2024. All rights reserved.