列表生成式
a = [0,1,2,3,4,5,6,7,8,9] for k,v in enumerate(a): a[k] = v+1 a = map(lambda x:x+1,a) a = [i+1 for i in a] a = [i*i if i > 5 else i+10 for i in a]
生成器
a = [0,1,2,3,4,5,6,7,8,9] a = (i*i if i > 5 else i+10 for i in a) print(next(a)) print(a.__next__()) 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(15) print(f.__next__()) print(‘生成器yield保存了函数的中断状态‘) print(f.__next__())
下面是一个吃包子的程序,模拟并发
import time def consumer(name): print("%s 准备吃包子了!" % name) while True: baozi = yield print("包子[%s]来了,被[%s]吃了" % (baozi,name)) def producer(name): c = consumer(‘李磊‘) c2 = consumer(‘杨帅‘) c.__next__() c2.__next__() print("%s开始准备做包子啦!" % name) for i in range(10): time.sleep(1) print("做了2个包子!") c.send(i) c2.send(i) producer(‘alex‘)
原文:http://www.cnblogs.com/wescker/p/6476836.html