生成器的一个实际用例是遍历无限序列的值。这是查找斐波那契数列前十项的示例。
def fib(a=0, b=1): """Generator that yields Fibonacci numbers. `a` and `b` are the seed values""" while True: yield a a, b = b, a + b f = fib() print(', '.join(str(next(f)) for _ in range(10)))
0、1、1、2、3、5、8、13、21、34