4.1 手动�历迭代器¶

问题¶

你想�历一个�迭代对象中的所有元素,但是��想使用for循环。

解决方案¶

为了手动的�历�迭代对象,使用 next() 函数并在代�中�获 StopIteration 异常。 比如,下�的例�手动读�一个文件中的所有行:

def manual_iter():
    with open('/etc/passwd') as f:
        try:
            while True:
                line = next(f)
                print(line, end='')
        except StopIteration:
            pass

通常�讲, StopIteration 用�指示迭代的结尾。 然而,如果你手动使用上�演示的 next() 函数的�,你还�以通过返回一个指定值�标记结尾,比如 None 。 下�是示例:

with open('/etc/passwd') as f:
    while True:
        line = next(f, None)
        if line is None:
            break
        print(line, end='')

讨论¶

大多数情况下,我们会使用 for 循环语�用��历一个�迭代对象。 但是,�尔也需�对迭代�更加精确的控制,这时候了解底层迭代机制就显得尤为��了。

下�的交互示例�我们演示了迭代期间所�生的基本细节:

>>> items = [1, 2, 3]
>>> # Get the iterator
>>> it = iter(items) # Invokes items.__iter__()
>>> # Run the iterator
>>> next(it) # Invokes it.__next__()
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
StopIteration
>>>

本章接下�几�节会更深入的讲解迭代相关技术,��是你先��解基本的迭代�议机制。 所以确�你已�把这章的内容牢牢记在心中。