cookbook 4. 迭代器和生成器

4.1 手动访问迭代器中的元素

不使用for循环打印, 为对底层迭代机制做更精细控制,手动访问可迭代对象的元素。 用next()函数,但是需要自己编写捕捉StopIteration异常(例一),或者要求next()返回为None(例二),并捕捉。 

# 例一: 捕捉异常
with open('/etc/password') as f:
    try:
        while True:
            line = next(f)
            print(line, end='')
    except StopIteration:
        pass
    

# 例二: 捕捉next()返回为None
with open('/etc/password') as f:
    while True:
        line = next(f,None)
        if line is None:
            break
        print(line, end='')

 4.2 委托迭代

构建一个自定义的容器对象, 内部持有一个list,tuple 或者其他的可迭代对象。

原文地址:https://www.cnblogs.com/lg100lg100/p/7995205.html