虽然
n
被称为
循环变量
名单绝对是
不
迭代器。它是可迭代对象,即和
可迭代的
,但它不是
迭代器
。iterable可以是迭代器本身,但并不总是。也就是说,迭代器是可迭代的,但并非所有的迭代器都是迭代器。如果是
list
它只是一个可迭代的。
它是一个可迭代的,因为它实现了
__iter__
方法,它返回一个迭代器:
从
Python Glossary
可迭代的
是:
能够一次返回一个成员的对象。的示例
和一些非序列类型,如dict、文件对象和
使用
__iter__()
或
__getitem__()
方法
Iterable可以在for循环中使用,也可以在许多其他地方使用
当可迭代对象为
作为参数传递给内置函数
iter()
,它返回一个
对象的迭代器。这个迭代器适合在
一组值。使用iterables时,通常不需要
调用iter()或自己处理迭代器对象。for语句
会自动为您创建一个临时未命名变量
因此,观察:
>>> x = [1,2,3]
>>> iterator = iter(x)
>>> type(iterator)
<class 'list_iterator'>
>>> next(iterator)
1
>>> next(iterator)
2
>>> next(iterator)
3
>>> next(iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
理解Python中的for循环很有启发性,例如:
for n in some_iterable:
等于:
iterator = iter(some_iterable)
while True:
try:
n = next(iterator)
except StopIteration as e:
break
Iterator,通过调用对象的
__iter公司__
方法,还实现
__iter公司__
而且
__next__
方法因此,检查某个对象是否是可迭代的一种简单方法是查看它是否实现了
下一个
方法
>>> next(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not an iterator
Python Glossary
一
迭代器
是:
表示数据流的对象。重复呼叫
迭代器
__next__()
方法(或将其传递给内置函数
next()
)返回流中的连续项。当没有更多数据时
迭代器对象已用完,对它的任何进一步调用
__下一个__()
Iterator需要具有
__iter__()
因此每个迭代器也是可迭代的,可以在大多数
接受其他迭代的位置。一个值得注意的例外是
尝试多次迭代的代码。容器对象
(例如列表)每次传递时都会生成一个新的迭代器
或在for循环中使用它。正在尝试使用
迭代器只返回使用过的相同的穷尽迭代器对象
容器
我已经用
next
函数,所以现在我想集中讨论粗体部分。
基本上,迭代器可以代替iterable,因为迭代器总是可迭代的。然而,迭代器只适用于单程。因此,如果我使用非迭代器可迭代,如列表,我可以这样做:
>>> my_list = ['a','b','c']
>>> for c in my_list:
... print(c)
...
a
b
c
还有这个:
>>> for c1 in my_list:
... for c2 in my_list:
... print(c1,c2)
...
a a
a b
a c
b a
b b
b c
c a
c b
c c
>>>
迭代器的行为几乎相同,所以我仍然可以这样做:
>>> it = iter(my_list)
>>> for c in it:
... print(c)
...
a
b
c
>>>
然而,迭代器不支持多次迭代(嗯,您可以使您的迭代器支持多次迭代,但通常不支持多次重复):
>>> it = iter(my_list)
>>> for c1 in it:
... for c2 in it:
... print(c1,c2)
...
a b
a c
这是为什么?回想一下迭代器协议的情况
for
在发动机罩下循环,并考虑以下因素:
>>> my_list = ['a','b','c','d','e','f','g']
>>> iterator = iter(my_list)
>>> iterator_of_iterator = iter(iterator)
>>> next(iterator)
'a'
>>> next(iterator)
'b'
>>> next(iterator_of_iterator)
'c'
>>> next(iterator_of_iterator)
'd'
>>> next(iterator)
'e'
>>> next(iterator_of_iterator)
'f'
>>> next(iterator)
'g'
>>> next(iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> next(iterator_of_iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
当我使用
iter()
在迭代器上,它返回自己!
>>> id(iterator)
139788446566216
>>> id(iterator_of_iterator)
139788446566216