一、生成器简介:
- 只有在调用时才生成相应的数据
- 只记录当前位置
- 只有一个方法__next__()
#!/usr/bin/env python
# -*- coding:utf-8 -*-
a = [i*2 for i in range(10)] #列表
print(a)
b = (i*2 for i in range(10)) #生成器generator
print(b)
结果:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
<generator object <genexpr> at 0x107027200>
二、yield和StopIteration
def fib(n):
a, b = 0, 1
for i in range(n):
yield b #print(b)改为yield b 即变为生成器
a,b = b,a+b
f = fib(10)
while True:
try:
x = f.__next__()
print(x)
except StopIteration as e:
print('error ',e.value)
break
三、generator和函数的执行流程不一样:
- 函数是顺序执行,遇到return语句或者最后一行函数语句就返回。
- 而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行
import time
def consumer(name):
print('%s 快来吃包子啊!' % name)
while True:
baozi = yield
print('包子%s来了,被%s吃啦' % (baozi,name))
def producer():
c1 = consumer('amber')
c2 = consumer('lucy')
c1.__next__()
c2.__next__()
for i in range(5):
c1.send(i)
c2.send(i)
producer()