【问题标题】:How to get the following output in asyncio gather如何在异步收集中获得以下输出
【发布时间】:2021-12-19 14:26:35
【问题描述】:

有没有办法我可以得到 result1result2 的 as_completed 结果 合并?

预期输出

[0, 0, 1, 1, 2, 2]

电流输出

[0, 1, 2, 0, 1, 2]

代码

import asyncio

async def sleep(i):
    await asyncio.sleep(i)
    return i

async def main():
    result1 = [sleep(i) for i in [2, 1, 0]]
    result2 = [sleep(i) for i in [2, 1, 0]]

    result1Gathered = asyncio.as_completed(result1)
    result2Gathered = asyncio.as_completed(result2)

    result = await asyncio.gather(*result1Gathered, *result2Gathered)

    print(result)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

【问题讨论】:

    标签: python async-await


    【解决方案1】:

    这是因为gather 返回给它的结果。

    您想要的不是gather,而是循环遍历as_completed 的结果。您可以使用itertools.chain 组合所有可迭代对象:

    from itertools import chain
    
    ...
    
    async def main():
        result1 = [sleep(i) for i in [2, 1, 0]]
        result2 = [sleep(i) for i in [2, 1, 0]]
    
        result = [await i for i in asyncio.as_completed(chain(result1, result2))]
    
        print(result)
    

    结果:

    [0, 0, 1, 1, 2, 2]
    

    【讨论】:

    • 谢谢,所以这不会阻塞我的事件循环?
    • 你也能解释一下为什么收集不能像我想象的那样工作吗?以0 为arg 的那个应该先完成吧?为什么默认情况下它们不是第一个?
    • 我知道这不是原始问题的一部分,但如果您也能回答这个问题,我将不胜感激,如果等待的长度不同,我将如何处理?如果我使用 zip_longest 将 None 作为填充值工作吗?
    • 此解决方案有效。
    • @Jake 请看我的编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 2016-02-11
    • 1970-01-01
    • 2019-11-04
    相关资源
    最近更新 更多