迭代器

简介

迭代器对象可以在 for 循环中使用:

x = [2, 4, 6]

for n in x:
    print (n)
2
4
6

其好处是不需要对下标进行迭代,但是有些情况下,我们既希望获得下标,也希望获得对应的值,那么可以将迭代器传给 enumerate 函数,这样每次迭代都会返回一组 (index, value) 组成的元组:

x = [2, 4, 6]

for i, n in enumerate(x):
    print ('pos', i, 'is', n)
pos 0 is 2
pos 1 is 4
pos 2 is 6

迭代器对象必须实现 __iter__ 方法:

x = [2, 4, 6]
i = x.__iter__()
print (i)
<list_iterator object at 0x7f21743c2748>

__iter__() 返回的对象支持 next 方法,返回迭代器中的下一个元素:

print (next(i))
2

当下一个元素不存在时,会 raise 一个 StopIteration 错误:

print (next(i))
print (next(i))
4
6
next(i)

    ---------------------------------------------------------------------------

    StopIteration                             Traceback (most recent call last)

    <ipython-input-23-a883b34d6d8a> in <module>
    ----> 1 next(i)
    

    StopIteration: 


很多标准库函数返回的是迭代器:

r = reversed(x)
print (r)
<list_reverseiterator object at 0x7f21743c25f8>

调用它的 next() 方法:

print (next(r))
print (next(r))
print (next(r))
6
4
2

自定义一个 list 的取反迭代器:

不会出现之前的问题: