Lambda expressions are a common form of writing for anonymous methods in Python programs, which are very simple to write, but at the expense of readability. Let's look at a brief introduction to lambda.
Grammar
Lambda [Parameter_list]:expression
The return value of a lambda expression is a function, [parameter_list] is a function parameter, and expression is a specific operation. Its corresponding non-anonymous method is written in the following way:
def function ([parameter_list]): expression
As in the following example:
# Function def func (N): return n + 1print(func (2))#Lambdalambda x:x+1Print (f)print(f (2))
The first is the addition of a normal non-anonymous function, and the second is the lambda representation of the anonymous function. The x in the lambda is the parameter of the expression return function, x+1 is the specific function content. Because the lambda expression returns an anonymous function, the print result is:
Of course, lambda expressions also have the following use cases:
#Multi-parameter casePrint("Multi-parameter case") Multi=Lambdax,y,z:x+y+ZPrint(multi ())#working with non-anonymous functionsPrint("working with non-anonymous functions")defNamedfunc (n):return Lambdax:n+xPrint(Namedfunc (2))#will print out function, equivalent to lambda x:2+xPrint(Namedfunc (2) (3))#will print out 5F= Namedfunc (2)Print(f (3))#equivalent to Namedfunc (2) (3)
The results are as follows:
Some small suggestions for lambda expressions in Python programs:
1. For simple logic processing, you can safely use lambda expressions, which is more concise
2. For complex logic processing, avoid using lambda expressions, poor readability, and error-prone (except Daniel)
lambda Expressions in Python