如何编写一个将方法输出组合在单个变量中的异步函数?

How to write an asyncio function that combines the output of method in single variable?

所以,我一直在阅读有关 asyncio 的内容。考虑以下示例:

def f(i):
    return i

现在,对于上述函数,如果我想从 1 循环到 10 以获得输出。我可以 [f(i) for i in range(10)]。使用 asyncio gather,我们可以这样做: asyncio.gather(*[f(i) for i in range(10)])他们俩return一个单子给我。 但是说,我想聚合这些值以获得总和。即

sum=0
for i in range(10):
    sum+=f(i)

有没有办法在 asyncio 中做到这一点?

您正在寻找 asyncio.as_completed:

sum = 0
for next_result in asyncio.as_completed([f(i) for i in range(10)]):
    sum += await next_result