Python的带下划线的lambda作为参数? [英] Python's lambda with underscore for an argument?

查看:102
本文介绍了Python的带下划线的lambda作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码是做什么的?

a = lambda _:True

根据我在交互式提示中阅读和测试的内容,它似乎是一个始终返回True的函数.

From what I read and tested in the interactive prompt, it seems to be a function that returns always True.

我理解正确吗?我希望了解为什么还要使用下划线(_).

Am I understanding this correctly? I hope to understand why an underscore (_) was used as well.

推荐答案

_是变量名.试试吧. (此变量名称通常是忽略变量的名称.可以说是占位符.)

The _ is variable name. Try it. (This variable name is usually a name for an ignored variable. A placeholder so to speak.)

Python:

>>> l = lambda _: True
>>> l()
<lambda>() missing 1 required positional argument: '_'

>>> l("foo")
True

因此,此lambda 需要一个参数.如果您想要一个不带参数的lambda 始终返回True,请执行以下操作:

So this lambda does require one argument. If you want a lambda with no argument that always returns True, do this:

>>> m = lambda: True
>>> m()
True

这篇关于Python的带下划线的lambda作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆