生成器和迭代器
- 节省空间
- 惰性运算:边循环边处理
- 列表生成使用[],生成器使用()
g = (i*i if i > 20 else i for i in a)
print(g)
print(next(g))
print(g.__next__())
print('-'*20)
for i in g:
print(i)
- yield 保存了函数的中断状态
def fib(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b = b,a+b
n += 1
return 'done'
f = fib(10)
print(f)
print(next(f))
print(next(f))
print('-'*20)
print(next(f))
print(next(f))
for i in f:
print(i)
- send 将外部参数传到函数的yield中断里
吃包子游戏
import time
def consumer(name):
print('%s 准备吃包子' % name)
while 1:
baozi = yield
print('包子[%s]来了,被[%s]吃了' %(baozi,name))
def producer(name):
c = consumer('Yaho')
c2 = consumer('Ali')
next(c)
next(c2)
print('开始做包子')
for i in range(10):
time.sleep(1)
print('%s 做了2个包子出来' %name)
c.send(i)
c2.send(i)
producer('Steven')