如何在python lambda中使用await

编程入门 行业动态 更新时间:2024-10-10 05:18:16
本文介绍了如何在python lambda中使用await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试做这样的事情:

I'm trying to do something like this:

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

但是我得到这个错误:

SyntaxError: 'await' outside async function

这是有道理的,因为lambda不是异步的.

Which makes sense because the lambda is not async.

我尝试使用 async lambda x:... ,但这会引发 SyntaxError:无效语法.

I tried to use async lambda x: ... but that throws a SyntaxError: invalid syntax.

Pep 492 状态:

可以提供异步lambda函数的语法,但是这种构造超出了本PEP的范围.

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

但是我无法确定该语法是否在CPython中实现.

But I could not find out if that syntax was implemented in CPython.

是否可以声明异步lambda或使用异步函数对列表进行排序?

Is there a way to declare an async lambda, or to use an async function for sorting a list?

推荐答案

您不能.没有异步lambda ,即使存在,您也不会将其作为键函数传递给 list.sort(),因为会调用键函数作为同步功能,并且没有等待.一个简单的解决方法是自己注释列表:

You can't. There is no async lambda, and even if there were, you coudln't pass it in as key function to list.sort(), since a key function will be called as a synchronous function and not awaited. An easy work-around is to annotate your list yourself:

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

请注意,列表推导中的 await 表达式仅在Python 3.6+中受支持.如果您使用的是3.5,则可以执行以下操作:

Note that await expressions in list comprehensions are only supported in Python 3.6+. If you're using 3.5, you can do the following:

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

更多推荐

如何在python lambda中使用await

本文发布于:2023-11-28 04:46:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   python   await   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!