亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

不確定為什么 StopIteration 不由“yield from”處理

不確定為什么 StopIteration 不由“yield from”處理

慕標琳琳 2021-09-11 10:52:52
查看“Fluent Python”書中解釋 的“雙向隧道”功能的以下示例代碼yield from,我有以下問題。from collections import namedtupleResult = namedtuple('Result', 'count average')# the subgeneratordef averager():  # <1>    total = 0.0    count = 0    average = None    while True:        term = yield  # <2>        if term is None:  # <3>            break        total += term        count += 1        average = total/count    return Result(count, average)  # <4># the delegating generatordef grouper(results, key):  # <5>    while True:  # <6>        results[key] = yield from averager()  # <7># the client code, a.k.a. the callerdef main(data):  # <8>    results = {}    for key, values in data.items():        group = grouper(results, key)  # <9>        next(group)  # <10>        for value in values:            group.send(value)  # <11>        group.send(None)  # important! <12>        print("wrapped up grouper")    print(results)data = {    'girls;kg':        [40.9, 38.5, 44.3, 42.2, 45.2, 41.7, 44.5, 38.0, 40.6, 44.5],    'girls;m':        [1.6, 1.51, 1.4, 1.3, 1.41, 1.39, 1.33, 1.46, 1.45, 1.43],    'boys;kg':        [39.0, 40.8, 43.2, 40.8, 43.1, 38.6, 41.4, 40.6, 36.3],    'boys;m':        [1.38, 1.5, 1.32, 1.25, 1.37, 1.48, 1.25, 1.49, 1.46],}StopIteration當我用下面的委托生成器替換上面的委托生成器時,為什么會出現異常?def grouper(results, key):    results[key] = yield from averager()從我到目前為止所學到的,從理論上講,刪除while True應該沒問題。group.send(None)將導致averager()協程break并返回Result(...),該 將被傳遞給委托生成器。然后委托生成器將通過將其分配Result(...)給results[key].但正在發生的事情如下。Traceback (mostrecent call last):  File "coroaverager3.py", line 111, in <module>    main(data)  File "coroaverager3.py", line 83, in main    group.send(None)  # important! <12>StopIteration任何見解?
查看完整描述

1 回答

  • 1 回答
  • 0 關注
  • 184 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號