如果我这样做的话:
a = range(9)
for i in a:
print(i)
# Must be exhausted by now
for i in a:
print(i)
# It starts over!Python的生成器,在引发StopIteration之后,通常停止循环。那么范围是如何产生这种模式的-它在每次迭代之后都会重新启动。
发布于 2014-12-16 10:03:39
正如其他人所指出的,range不是生成器,而是序列类型(如list),使其成为与iterator不同的iterable。
iterable、iterator和generator之间的差异是微妙的(至少对于刚接触python的人来说是如此)。
iterator提供了一个__next__方法,并且可以耗尽,从而引发StopIteration。iterable是一个对其内容提供iterator的对象。每当调用其__iter__方法时,它都会返回一个新的迭代器对象,因此您可以(间接地)对它进行多次迭代。generator是一个函数,它返回一个iterator,该函数可能会被耗尽。for循环自动查询任何iterable的iterator。这就是为什么您可以编写for x in iterable: pass而不是for x in iterable.__iter__(): pass或for x in iter(iterable): pass。所有这些都在文档中,但IMHO有点难找到。最好的起点可能是术语表。
发布于 2014-12-16 09:18:39
range是一种不可变的序列类型。迭代它并不会耗尽它。
>>> a = iter(range(9)) # explicitly convert to iterator
>>>
>>> for i in a:
... print(i)
...
0
1
2
3
4
5
6
7
8
>>> for i in a:
... print(i)
...
>>>https://stackoverflow.com/questions/27501067
复制相似问题