一·迭代器
可以直接作用于for循环的对象统称为可迭代对象(Iterable)。
可以被next()函数调用并不断返回下一个值的对象称为迭代器(Iterator)。
所有的Iterable均可以通过内置函数iter()来转变为Iterator。
对迭代器来讲,有一个__next__()就够了。在你使用for 和 in 语句时,程序就会自动调用即将被处理的对象的迭代器对象,然后使用它的__next__()方法,直到监测到一个StopIteration异常。
相关BIF: iter() next()
一下为IDLE环境下的演示
>>> string = 'tecent'
>>> it = iter(string)
>>> next(it)
't'
>>> next(it)
'e'
>>> next(it)
'c'
>>> next(it)
'e'
>>> next(it)
'n'
>>> next(it)
't'
>>> next(it)
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
next(it)
StopIteration
>>>
下面是for迭代的工作原理
string