【问题标题】:How to sort sequence based on a coroutine?如何根据协程对序列进行排序?
【发布时间】:2021-01-02 20:14:11
【问题描述】:

使用简单的实现,例如:

import asyncio

async def get_priority(value):
    # Simulate sending out network request.
    await asyncio.sleep(0.5)
    return value

values = [1, 2, 3]
sorted_values = await sorted(values, key=get_priority)

(假设顶级await 被包裹在async def 中)

sorted 假设 key 函数是同步的,它会尝试比较协程本身而不是底层值,从而导致 TypeError

当我希望键函数成为协程时,如何对序列进行排序?我可以自己编写sorted 实现,但特别想知道我是否可以使用asyncio 以某种方式提取sorted 之外的异步密钥计算,所以我可以坚持使用标准库。

【问题讨论】:

    标签: python sorting asynchronous async-await python-asyncio


    【解决方案1】:

    最终偶然发现了Implement async/await in sort function of arrays javascript,它引用了Schwartzian transform,其中对值进行排序的优先级是预先计算的,并与原始值一起存储。下面是 Python 中的一个实现:

    import asyncio
    from operator import itemgetter
    
    async def get_priority(value):
        # Simulate sending out network request.
        await asyncio.sleep(0.5)
        return value
    
    values = [1, 2, 3]
    value_priorities = await asyncio.gather(*map(get_priority, values))
    sorted_values = [value for value, _ in sorted(
        zip(values, value_priorities),
        key=itemgetter(1)
    )]
    

    【讨论】:

      猜你喜欢
      • 2021-08-04
      • 1970-01-01
      • 2015-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多