本文已参与「新人创作礼」活动,一起开启掘金创作之路
• 生成器(generator):生成器是一类特殊的迭代器。
• 生成器每次在迭代时可以返回一个或者多个值,它可以记录当前状 态。
• 生成器的创建方式:
– 使用yield关键字。
– 使用生成器表达式(推导式)。
生成器推导式
• 推导式形式:
– (推导式):G = ( x*2 for x in range(5)
– 判断是否是生成器:
yield创建生成器
• 使用yield创建生成器:
– 通过yield创建一个产生斐波那契数列数列的生成器。
生成器取值
• 生成器可以使用next和send取值:
– next,获取下一个元素。
– send,获取下一个元素,同时可以向生成器中传递一个值。
– next等同于send(None)。
– 第一次取值时,需要使用next或者send(None)
执行过程:
– 4 - 1 - 2 - 3 - 5 - 1 - 2 …… - 6
```py
def fib(n): current = 0 num1, num2 = 0, 1 while current < n: num = num1 # 1 num1, num2 = num2, num1+num2 # 2 current += 1 yield num # 3 return 'done' # 6 g=fib(5) # 4 next(g) # 5 ```
• 使用yield声明函数为生成器。
• 当程序执行到yield处时,生成器函数暂停,等待下一次唤醒(next、 send)。
– 并且返回当前值。
– 和return相似,但是程序暂停而不是结束。
通过 yield 创建生成器函数:
```py def fib(n): current = 0 num1, num2 = 0, 1 while current < n: num = num1 num1, num2 = num2, num1+num2 current += 1 yield num return 'done' g=fib(5) while True: try: x = next(g) print("value:%d"%x) except StopIteration as e: print("生成器返回值:%s"%e.value) break
```
除了使用 next 方法以外,还可以使用 send 方法唤醒生成器,相比于 next 方法,send 在唤醒生成器时还 可以向断点处传入一个数据。
```py def gen(): i = 0 while i<5: temp = yield i print(temp) i+=1 f = gen() next(f)
0 f.send('haha') haha 1 next(f) None 2 ```