Flask接口签名sign原理与实例代码浅析
246
2022-09-04
协程之生成器yield from(协程 实现)
yield from 你知道做什么那些事情吗?
帮我们迭代:
#python3.3新加了yield from语法from itertools import chainmy_list = [1,2,3]my_dict = { "sunlong001":" "sunlong002":"my_chain(*args, **kwargs): for my_iterable in args: # yield from my_iterable for value in my_iterable: yield valuefor value in my_chain(my_list, my_dict, range(5,10)): print(value)
yield from my_iterable等价于: | for value in my_iterable: |
让协程返回值
#让协程返回值#定义一个求平均值的协程from collections import namedtupleResult = namedtuple('Result','cunt average')def averager(): total = 0 count = 0 average = None while True: term = yield if term is None: break total += term count += 1 average = total/count return Result(count,average)coro_avg = averager()coro_avg.send(None)coro_avg.send(10)coro_avg.send(20)coro_avg.send(9)# coro_avg.send(None)try: coro_avg.send(None)except StopIteration as exc: result = exc.valueprint(result)
yield from的主要功能是打开双向通道,把最外层的调用方法与最内层的子生成器连接起来,这样二者可以直接发送和产出值,还可以直接传入异常,而不用在位于中间的协程中添加大量处理异常的代码,有了这个机构,
协程可以通过以前不可能的方式委托职责
委派生成器;
子生成器;
委派生成器在yield from 表达式处暂停时,调用放可以直接把数据发给子生成器,子生成器再把产出的值发给调用方,子生成其返回之后,解释器会抛出StopIteration异常,并把返回值附加到异常对象上,此时委派生成器会恢复
#让协程返回值#定义一个求平均值的协程from collections import namedtupleResult = namedtuple('Result','cunt average')#子生成器def averager(): total = 0 count = 0 average = None while True: term = yield if term is None: break total += term count += 1 average = total/count return Result(count,average)#委派生成器def grouper(results,key): while True: results[key] = yield from averager()#客户端代码 调用方def main(data): results = {} for key,values in data.items(): group = grouper(results,key) next(group) for value in values: group.send(value) group.send(None) print(results)data = { 'girls;kg': [40.9,38.5,42.2,45.2,41.7,44.5,38.0], 'girls:m': [1.6,1.51,1.3,1.41,1.39,1.33,1.46],}if __name__ == '__main__': main(data)#输出结果# {'girls;kg': Result(cunt=7, average=41.57142857142857), 'girls:m': Result(cunt=7, average=1.4285714285714286)}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~