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)
)]