[英]What are the advantages of lambda expression over regular function?
From the docs : 从文档:
Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you're too lazy to define a function.
Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you're too lazy to define a function.
Is there an actual advantage using lambda expression over regular functions like a runtime advantage or an aesthetic one?使用 lambda 表达式相对于常规函数(如运行时优势或美学函数)是否有实际优势? Is there cases where lambda expression are an absolute necessity?
在某些情况下 lambda 表达式是绝对必要的吗? I feel like they are just a limited version of functions as they can contain only 1 argument.
我觉得它们只是函数的有限版本,因为它们只能包含 1 个参数。
I'am not sure to grasp their utility and the concept as a whole beyond the fact that it's an implementation of Alonso Church lambda calculus.除了它是 Alonso Church lambda 微积分的实现这一事实之外,我不确定它们的效用和整个概念。
The following compute the product of 2 numbers, and I find the function version clearer.以下计算 2 个数字的乘积,我发现 function 版本更清晰。
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
def times(a,b):
return a*b
print (times(2,11))
Lambdas can have multiple arguments. Lambda 可以有多个 arguments。 A place I find they fit nicely is when I'm creating functional dictionaries.
我发现它们非常适合的一个地方是当我创建功能字典时。 Ex:
前任:
res = input("Unexpected Input Here")
choices = {
"x": lambda *data: data[1] / data[0]
"y": lambda *data: data[1] - data[0],
"z": lambda data1, data2: data2 * data1
...
}
choices[res](100, 20)
It's not worth it for me to write these out to multiple functions.将这些写到多个函数中对我来说是不值得的。 This is a fairly trivial example but I use this pattern for HTTP request validation, pandas data manipulation, etc. It's great because you can also iterate over dictionaries and you can create a pipeline of functions (based on specialized logic to skip certain keys, potentially based on the value instance via
isinstance
).这是一个相当简单的示例,但我将此模式用于 HTTP 请求验证、pandas 数据操作等。这很棒,因为您还可以遍历字典,并且可以创建函数管道(基于专门的逻辑来跳过某些键,可能基于通过
isinstance
的值实例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.