Python 的 lambda 带有下划线作为参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29767310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python's lambda with underscore for an argument?
提问by laycat
What does the following code do?
下面的代码有什么作用?
a = lambda _:True
From what I read and tested in the interactive prompt, it seems to be a function that returns always True
.
从我在交互式提示中阅读和测试的内容来看,它似乎是一个返回 always 的函数True
。
Am I understanding this correctly? I hope to understand why an underscore (_
) was used as well.
我理解正确吗?我希望能理解为什么_
还使用了下划线 ( )。
采纳答案by miku
The _
is variable name. Try it.
(This variable name is usually a name for an ignored variable. A placeholder so to speak.)
该_
是变量名。尝试一下。(这个变量名通常是一个被忽略变量的名称。可以说是一个占位符。)
Python:
Python:
>>> l = lambda _: True
>>> l()
<lambda>() missing 1 required positional argument: '_'
>>> l("foo")
True
So this lambda does require one argument. If you want a lambda with no argumentthat always returns True
, do this:
所以这个 lambda确实需要一个参数。如果你想要一个没有参数的 lambda总是返回True
,请执行以下操作:
>>> m = lambda: True
>>> m()
True
回答by haccks
Underscore _
is a valid identifier and is used here as a variable name. It will always return True
for the argument passed to the function.
下划线_
是一个有效的标识符,在这里用作变量名。它将始终返回True
传递给函数的参数。
>>>a('123')
True
回答by miku
it seems to be a function that returns True regardless.
它似乎是一个无论如何都返回 True 的函数。
Yes, it is a function (or lambda) that returns True. The underscore, which is usually a placeholder for an ignored variable, is unnecessary in this case.
是的,它是一个返回 True 的函数(或 lambda)。的下划线,这通常是用于忽略可变的占位符,在这种情况下是不必要的。
An example use casefor such a function (that does almost nothing):
此类函数的示例用例(几乎什么都不做):
dd = collections.defaultdict(lambda: True)
When used as the argument to a defaultdict, you can have True
as a general default value.
当用作defaultdict的参数时,您可以将其True
作为一般默认值。
回答by hyades
Lambda means a function. The above statement is same as writing
Lambda 表示函数。上面的语句和写一样
def f(_):
return True
For lambda a variable needs to be present. So you pass it a variable called _
(Similarly you could pass x
, y
..)
对于 lambda,需要存在一个变量。所以你传递给它一个名为_
(同样你可以传递x
,y
..)
回答by ?ukasz Rogalski
Underscore is a Python convention to name an unused variable (e.g. static analysis tools does not report it as unused variable). In your case lambda argument is unused, but created object is single-argument function which always returns True
. So your lambda is somewhat analogous to Constant Functionin math.
下划线是 Python 命名未使用变量的约定(例如,静态分析工具不会将其报告为未使用变量)。在您的情况下,未使用 lambda 参数,但创建的对象是单参数函数,它始终返回True
. 所以你的 lambda 有点类似于数学中的常量函数。
回答by IdleCustard
Below is the line of code in question:
下面是有问题的代码行:
a = lambda _:True
It creates a function having one input parameter: _
. Underscore is a rather strange choice of variable name, but it is just a variable name. You can use _
anywhere, even when not using lambda functions. For example, instead of....
它创建了一个具有一个输入参数的函数:_
。下划线是一个相当奇怪的变量名选择,但它只是一个变量名。_
即使不使用 lambda 函数,您也可以在任何地方使用。例如,而不是......
my_var = 5
print(my_var)
You could write:
你可以写:
_ = 5
print(_)
However, there was a reason that _
was used as the name of parameter name instead of something like x
or input
. We'll get to that in a moment.
但是,有一个原因_
被用作参数名称的名称而不是像x
or之类的东西input
。我们稍后会讲到。
First, we need to know that the lambda-keyword constructs a function, similar to def
, but with different syntax. The definition of the lambda function, a = lambda _:True
, is similar to writing:
首先,我们需要知道 lambda-keyword 构造了一个函数,类似于def
,但语法不同。lambda 函数 的定义a = lambda _:True
类似于写法:
def a(_):
return True
It creates a function named a
with an input parameter _
, and it returns True
. One could have just as easily written a = lambda x:True
, with an x
instead of an underscore. However, the convention is to use _
as a variable name when we do not intend to use that variable. Consider the following:
它创建一个以a
输入参数命名的函数_
,并返回True
。人能够很容易地写a = lambda x:True
,用x
的,而不是下划线。但是,约定是_
在我们不打算使用该变量时将其用作变量名。考虑以下:
for _ in range(1, 11):
print('pear')
Notice that the loop index is never used inside of the loop-body. We simply want the loop to execute a specified number of times. As winklerrr
has written, "the variable name _
is [...] like a "throw-away-variable", just a placeholder which is of no use. "
请注意,循环索引永远不会在循环体内部使用。我们只是想让循环执行指定的次数。正如winklerrr
所写的那样,“变量名称_
[...] 就像一个“扔掉的变量”,只是一个没有用的占位符。”
Likewise, with ``a = lambda x:Truethe input parameter is not used inside the body of the function. It does not really matter what the input argument is, as long as there is one. The author of that lambda-function wrote
_
instead of something like x
, to indicate that the variable would not be used.
同样,对于 ``a = lambda x:True ,输入参数不在函数体内使用。输入参数是什么并不重要,只要有一个。那个 lambda 函数的作者写了
_
而不是像x
, 来表明不会使用该变量。
Note that the lambda doeshave an argument; So, writing
请注意,lambda确实有一个参数;所以,写
a()
, will raise an error.
a()
, 会引发错误。
If you want a lambda with no argument write something like this:
如果你想要一个没有参数的 lambda,写这样的:
bar = lambda: True
Now calling bar()
, with no args, will work just fine.
A lambda which takes no arguments need not always return the same value:
现在调用bar()
,没有参数,将工作得很好。不带参数的 lambda 不必总是返回相同的值:
import random
process_fruit = lambda : random.random()
The lambda function above is more complex that just a something which always returns the same constant.
上面的 lambda 函数更复杂,它只是一个总是返回相同常量的东西。
One reason that programmers sometimes us the lambda
keyword instead of def
is for functions which are especially short and simple. Note that a lambda
definition can usually fit all on one line, whereas, it is difficult to do the same with a def statement. Another reason to use lambda
instead of def
sf when the function will not be used again. If we don't want to call the function again later, then there is no need to give the function a name. For example consider the following code:
程序员有时使用lambda
关键字而不是关键字的原因之一def
是对于特别简短和简单的函数。请注意,lambda
定义通常可以放在一行中,而使用 def 语句很难做到这一点。当函数不再使用时,使用lambda
代替def
sf 的另一个原因。如果我们以后不想再次调用该函数,则无需为该函数命名。例如,考虑以下代码:
def apply_to_each(transform, in_container): out_container = list() for idx, item in enumerate(container, 0): out_container[idx] = transform(item) return out_container
def apply_to_each(transform, in_container): out_container = list() for idx, item in enumerate(container, 0): out_container[idx] = transform(item) return out_container
Now we make the following call:
现在我们进行以下调用:
squares = apply_to_each(lambda x: x**2 range(0, 101))
Notice that lambda x: x**2
is not given a label. This is because we probably won't call it again later, it was just something short and simple we needed temporarily.
请注意,lambda x: x**2
没有给定标签。这是因为我们以后可能不会再调用它,它只是我们暂时需要的一些简短而简单的东西。
The fact that lambda functions need not be given a name is the source of another name to describe them: "anonymous functions."
lambda 函数不需要命名这一事实是描述它们的另一个名称的来源:“匿名函数”。
Also note that lambda-statements are like a function-call in that they return a reference to the function they create. The following is illegal:
另请注意,lambda 语句类似于函数调用,因为它们返回对其创建的函数的引用。以下是非法的:
apply_to_each(def foo(x): x**2 , range(0, 101))
Whereas, apply_to_each(lambda x: x**2 range(0, 101))
is just fine.
而,apply_to_each(lambda x: x**2 range(0, 101))
就好了。
So, we use lambda
instead of def
and _
instead of a long variable name when we want something short, sweet and probably won't want use again later.
所以,当我们想要一些简短的、甜蜜的并且以后可能不想再次使用的东西时,我们使用lambda
而不是def
和_
代替长变量名。