*包含yield语句的生成器函数调用后,生成生成器对象的时候,生成器函数的函数体不会立即执行
*next(generator) 会从函数的当前位置向后执行到之后碰到的第一个yield语句,会弹出值,并暂停
函数执行
*再次调用next函数,和上一条一样的处理过程
*继续调用next函数,生成器函数如果结束执行了(显式或隐式调用了return语句),会抛出
*StopIteration异常
1、无限循环
def counter(): i = 0 while True: i += 1 yield i c = counter() print(next(c)) print(next(c)) print(next(c))
2、计数器
def inc(): def counter(): i = 0 while True: i += 1 yield i c = counter() return lambda : next(c) foo = inc() print(foo()) print(foo()) print(foo())
3、斐波那契数列
def fib(): a = 0 b = 1 while True: yield b a, b = b, a + b f = fib() for i in range(1, 102): print(i, next(f))
4、自定义map函数
def mymap(func, iterable, /): for i in iterable: yield func(i) print(dict(mymap(lambda x: (x, x+1), range(5))))



