生成器的阐释
1 # def xiadan(): 2 # ret = [] 3 # for i in range(10): 4 # ret.append('母鸡下蛋%s' %i) 5 # return ret 6 # l = xiadan() 7 # print(l) 8 9 # def xiadan(): 10 # for i in range(100): 11 # yield '母鸡下蛋%s' %i 12 # res = xiadan() 13 # print(res.__next__()) 14 # print(res.__next__()) ##生成器只能遍历一次 15 16 17 # def test(): 18 # print('开始了') 19 # 20 # fisrt = yield 1 21 # print('第一次',fisrt) 22 # 23 # yield 2 24 # print('第二次') 25 # t = test() 26 # res = t.__next__() 27 # res = t.__next__() 28 # 29 # print(res) 30 # t.send(None) #可以触发生成器执行 31 # res = t.send('函数停留在哪儿,我就在哪儿赋值') #可以触发生成器执行 32 # print(res) 33 34 # {'name':'袁','qian':1} 35 # {'name':'里','qian':2} 36 # {'name':'三','qian':3} 37 # {'name':'四','qian':4} 38 # {'name':'五','qian':5} 39 # 40 41 # def get_polulation(): 42 # ret = [] 43 # with open('人口普查.py','r',encoding='utf-8') as f: 44 # for i in f: 45 # ret.append(i) 46 # return ret 47 # l = get_polulation() 48 # 49 # print(l) 50 51 52 # def get_polulation(): 53 # 54 # with open('人口普查.py','r',encoding='utf-8') as f: 55 # for i in f: 56 # yield i 57 # l = get_polulation() 58 # # l1 = eval(l.__next__()) 59 # print(type(l1)) 60 # res = 0 61 # for p in l: 62 # pp = eval(p) 63 # print(pp['qian']) 64 # res+=pp['qian'] 65 # print(res) 66 67 # a = sum(eval(i)['qian'] for i in l) 68 # 69 # print(a) 70 71 72 73 74 # 生产者消费模型 75 76 # import time 77 # def producer(): 78 # ret = [] 79 # for i in range(10): 80 # time.sleep(0.1) 81 # ret.append('包子%s' %i) 82 # return ret 83 # 84 # def consumer(res): 85 # for index,baozi in enumerate(res): 86 # time.sleep(0.1) 87 # print('第%s几回,吃了%s' %(index,baozi)) 88 # 89 # res = producer() 90 # 91 # consumer(res) 92 93 # def text(): 94 # print('你好呀 臭弟弟') 95 # yu = yield 1 96 # print('奥利给',yu) 97 # yield 2 98 # print('精神小伙') 99 # yield 999 100 # 101 # l = text() 102 # print(l.__next__()) 103 # # print(l.__next__()) 104 # # print(l.__next__()) 105 # l.send(None) 106 107 # import time 108 # def consumer(name): 109 # print('我是[%s],我准备开始吃包子了' %name) 110 # while True: 111 # baozi = yield 112 # time.sleep(0.2) 113 # print('%s 很开心的把[%s]喝了' %(name,baozi)) 114 # 115 # def producer(): 116 # c1 = consumer('wanqi') 117 # c2 = consumer('yuanhao') 118 # c1.__next__() 119 # c2.__next__() 120 # for i in range(10): 121 # time.sleep(0.5) 122 # c1.send('包子 %s' %i) 123 # c2.send('包子%s' %i) 124 # producer()
Never compromise.