【11.6】生成器进阶--yield from
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 4 final_result = {} 5 6 7 # 子生成器 8 def sales_sum(pro_name): 9 total = 0 10 nums = [] 11 while True: 12 x = yield 13 print(pro_name+'销量: ', x) 14 if not x: 15 break 16 total += x 17 nums.append(x) 18 return total, nums 19 20 21 # 委托生成器 22 def middle(key): 23 while True: 24 final_result[key] = yield from sales_sum(key) 25 print(key+'销量统计完成!!.') 26 27 28 # 调用方 29 def main(): 30 data_sets = { 31 '小米9': [1200, 1500, 3000], 32 '小米8': [28, 55, 98, 108], 33 '小米5': [200, 560, 778, 70], 34 } 35 for key, data_set in data_sets.items(): 36 print('start key:', key) 37 m = middle(key) 38 # 预激middle协程 39 m.send(None) 40 for value in data_set: 41 # 给协程传递每一组的值 42 m.send(value) 43 # 结束 44 m.send(None) 45 print('final_result:', final_result) 46 47 48 if __name__ == '__main__': 49 main()
start key: 小米9 小米9销量: 1200 小米9销量: 1500 小米9销量: 3000 小米9销量: None 小米9销量统计完成!!. start key: 小米8 小米8销量: 28 小米8销量: 55 小米8销量: 98 小米8销量: 108 小米8销量: None 小米8销量统计完成!!. start key: 小米5 小米5销量: 200 小米5销量: 560 小米5销量: 778 小米5销量: 70 小米5销量: None 小米5销量统计完成!!. final_result: {'小米9': (5700, [1200, 1500, 3000]), '小米8': (289, [28, 55, 98, 108]), '小米5': (1608, [200, 560, 778, 70])}
yield from最主要的用法
1 # main调用方、g1(委托生成器)、gen 子生成器 2 # yield from会在调用方与子生成器之间建立一个双向通道 3 def g1(gen): 4 yield from gen 5 6 7 def main(): 8 g = g1() 9 g.send(None)
yield from 处理了StopIteration的异常
yield from 其他用法
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # python3.3新加了yield from语法 4 5 6 from itertools import chain 7 8 9 my_list = [1, 2, 3] 10 my_dict = { 11 'zy1': 'http://projectsedu.com', 12 'zy2': 'http://www.imooc.com' 13 } 14 15 16 # yield from iterable(可迭代对象) 17 def my_chain(*args, **kwargs): 18 for my_iterable in args: 19 yield from my_iterable 20 # for value in my_iterable: 21 # yield value 22 23 24 for value in my_chain(my_list, my_dict, range(5, 10)): 25 print(value)
1 2 3 zy1 zy2 5 6 7 8 9