This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together
Anonymous functions (lambda expressions)
Functions are “first-class citizens” in Python, so let’s review the advantages of functions:
- Reduce code duplication
- Modular code
But have we ever thought that if we need a function that is short and only needs to be used once (without having to call it again), then we need to define a function with a name?
The answer is no, and here we can use anonymous functions to do just that.
Let’s take the square of a number. Let’s define a function:
def square(x):
return x**2
square(3)
Copy the code
Lambda expressions can be written like this:
square = lambda x: x**2
square(3)
Copy the code
Based on the above example, lambda expressions are actually quite simple to use as follows:
lambda argument1, argument2,..... : expressionCopy the code
Next, the map, Filter, and Reduce functions, used in conjunction with lambda expressions, come into their own.
The map function
The map function is used as follows:
map(function, iterable)
Copy the code
Function is applied to each element of iterable and returns a new traversable collection.
A = b = [1, 2, 3, 4, 5] map (lambda x: x * 2, a) print (list) (b) # [2, 4, 6, 8, 10]Copy the code
The filter function
The filter function is used as follows:
filter(function, iterable)
Copy the code
Function evaluates each element of iterable and returns a new set of iterable elements that are all True.
A = b = [6] filter (lambda x: x % = = 0, 2 a) print (list) (b) # (2, 4, 6)Copy the code
The reduce function
The reduce function is used as follows:
reduce(function, iterable)
Copy the code
Function takes two arguments, representing each element of iterable and the result of the last operation, and returns a value. Note here that we need to import reduce from funcTools.
From functools import reduce a = [1,2,3,4] b = reduce(lambda x,y: x*y,a) print(b) # 24 1*2*3*4Copy the code
conclusion
- Lambda expressions
- Map, Filter, and Reduce functions