如何在 python lambda 中使用等待

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

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

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: invalid syntax.

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?

推荐答案

你不能.没有async 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 中使用等待

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

发布评论

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

>www.elefans.com

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