2016-11-22 77 views
4

我试图做这样的事情:如何使用等候在Python拉姆达

mylist.sort(key=lambda x: await somefunction(x)) 

,但我得到这个错误:

SyntaxError: 'await' outside async function 

这是有道理的,因为拉姆达不是异步。我试过使用async lambda x: ...但是抛出了SyntaxError: invalid syntax

Pep 492状态:

Syntax for asynchronous lambda functions could be provided, but this construct is outside of the scope of this PEP.

,但我无法找出如果语法是CPython的实现。

有没有办法来声明异步lambda,或使用异步函数来排序列表?

回答

8

你不能。没有async lambda,即使有,你也没有将它作为list.sort()的关键函数传递,因为一个关键函数将被称为同步函数而不是等待。一个简单的解决办法是自己注释列表:

mylist_annotated = [(await some_function(x), x) for x in mylist] 
mylist_annotated.sort() 
mylist = [x for key, x in mylist_annotated] 
+0

我得到一个'语法错误:“等待”的内涵是不supported'表情,所以我不得不这样做(备查): mylist_annotated = [] 用于MYLIST X: mylist_annotated.append((等待some_function(X)中,x)) mylist_annotated.sort() MYLIST = [X为键,X在mylist_annotated] 现在它的工作原理,谢谢! – iCart

+3

@iCart对,这是Python 3.5的一个限制,它在即将推出的Python 3.6中被解除了。 –