迭代器与生成器01-手动遍历迭代器 / 代理迭代 / 使用生成器创建新的迭代模式 / 实现迭代器协议

手动遍历迭代器

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

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

代理迭代

  • __iter__ ()
    iter ()方法,是将迭代操作代理到容器内部的对象上去。比如:
class Node():
    def __init__(self, value):
        self._value = value
        self._children = []

    def __repr__(self):
        return 'Node({!r})'.format(self._value)

    def add_child(self, node):
        self._children.append(node)

    def __iter__(self):
        return iter(self._children)

if __name__ == '__main__':
    root = Node(0)
    child1 = Node(1)
    child2 = Node(2)
    root.add_child(child1)
    root.add_child(child2)
    # Outputs Node(1), Node(2)
    for ch in root:
        print(ch)     #Node(1)
                      #Node(2)

使用生成器创建新的迭代模式

生产某个范围内浮点数的生成器

#定义一个方法,返回一个可迭代对象
def frange(start, stop, increment):
    x = start
    while x < stop:
        yield x
        x += increment

#使用for遍历结果  
for n in frange(0, 4, 0.5):
print(n)

#或者使用list(),直接例表化
print(list(frange(0, 4, 0.5)))

一个函数中需要有一个 yield 语句即可将其转换为一个生成器。跟普通函数不同
的是,生成器只能用于迭代操作
一个生成器函数主要特征是它只会回应在迭代中使用到的 next 操作。

猜你喜欢

转载自blog.csdn.net/xiangchi7/article/details/82564415
今日推荐