Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何基于协同程序对序列进行排序?_Python_Sorting_Asynchronous_Async Await_Python Asyncio - Fatal编程技术网

Python 如何基于协同程序对序列进行排序?

Python 如何基于协同程序对序列进行排序?,python,sorting,asynchronous,async-await,python-asyncio,Python,Sorting,Asynchronous,Async Await,Python Asyncio,使用一个简单的实现,如: 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中

使用一个简单的实现,如:

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
假设键函数是同步的,它将尝试比较协程本身而不是底层值,从而导致
TypeError

当我希望键函数是一个协程时,如何对序列进行排序?我可以自己编写
sorted
实现,但特别想知道我是否可以使用
asyncio
sorted
之外提取异步键计算,这样我就可以坚持使用标准库了。

最后遇到了一个问题,它引用了,其中,对值进行排序的优先级将预先计算并与原始值一起存储。下面是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)
)]