Python lambda() Function can simplify the program , We can lambda An expression is a simplified way to write a function , It can determine the output value according to the input value .
Usually Python When defining a function, you need to give the function name , however lambda The function name is not required , So we call it lambda Is an expression of anonymous functions . The syntax is as follows .
lambda parameter list , … : Expression where the colon before the expression “:” Don't omit , And can't use return sentence . for example , Transfer mathematical functions f(x)=3x-1 It's written in lambda expression ,Python The code is as follows :
result = lambda x : 3*x-1 #lambda() function
print(result(3)) # Output value 8
in other words “:” On the left is the parameter , On the right are expressions or blocks . For the purposes of this example ,“:” On the right is the expression 3*x-1, The number of parameters on the left is 1.
that Python Custom functions and lambda() What's the difference between functions ? Here is a simple example to illustrate ,Python The code is as follows :
def formula(x, y): # Custom function
return 3*x+2*y
formula = lambda x, y : 3*x+2*y # Express lambda There are two parameters
print(formula (5,10)) # Pass in two values to let lambda() Functions do operations , Output value 35
The above program code uses custom functions and lambda() Functions in two ways , We can observe that custom functions are similar to lambda() Functions have the following differences :