An overview of the
The biggest difference between an anonymous function and a function defined by def is that an anonymous function is created to return the function itself. The expression itself returns the value, whereas def is created to assign a value to a variable name. In Python, We create anonymous functions using the lambda keyword. Here is the form of the anonymous function lambda expression: lambda arg1,arg2,….. Argn :expression The following are some features of lambda:
- Lambda is an expression, not a statement, which means we can use lambda in any scenario where expressions can be used.
- The body of a lambda is an expression, that is, like a function defined by def, a lambda has a function body, but the body of a lambda is only an expression, so what it can do is much more limited.
Lambda use
Anonymous function without parameters
Lambda can be passed directly to a variable, just like calling a normal function
B = lambda :True
print(B())
# is equivalent to
def BF(a):
return True
print(BF())
Copy the code
Example results:
True
True
Copy the code
Parameter anonymous function
Support for multiple parameters
Parameter Has no default value
two_sum = lambda x, y: x + y
# Equivalent to:
def two_sum(x, y): return x + y
print(two_sum(1.2))
Copy the code
Example results:
3
Copy the code
Parameter with default value
sum_with_100 = lambda x, y=100: x + y
# Equivalent to:
def sum_with_100(x, y=100): return x + y
print(sum_with_100(200))
Copy the code
Example results:
300
Copy the code
Pass the parameter from behind
In the previous example we assigned a lambda anonymous function to a variable, passing arguments in a manner similar to the function def defines. We can pass arguments directly after lambda:
two_sum = (lambda x, y: x + y)(3.4)
print(two_sum)
Copy the code
Example results:
7
Copy the code
Use nested
Build a simple closure by nesting a lambda into a normal function, with the lambda function itself as the return value
def sum(x):
return lambda y: x + y
sum_with_100 = sum(100)
result = sum_with_100(200)
print(result)
Copy the code
Example results:
300
Copy the code
Some examples
1. Find the minimum of two values in combination with a ternary expression
lower = lambda x,y: x if x<y else y
print(the lower (7100))Copy the code
Example results:
7
Copy the code
2. Sort a dictionary key
d = [{"order":3}, {"order":1}, {"order":2}]
Sort by order key value
d.sort(key=lambda x:x['order'])
print(d)
Copy the code
Example results
[{'order': 1}, {'order': 2}, {'order': 3}]
Copy the code