Lambda is the keyword. Filter,map,reduce is a built-in function.
Lambda:Implements a single-line minimum function in Python.
g = Lambda x:x * 2 #相当于def g (x): return x*2
Map function
The map () function receives two parameters, one is a function, the other is a sequence, and map passes the incoming function to each element of the sequence sequentially, returning the result as a new list.
To illustrate:
For example, we have a function f (x) =x2, to function in a list [1, 2, 3, 4, 5, 6, 7, 8, 9], you can use map () to achieve the following:
Now, we use Python code to implement:
>>> def f (x): ... return x * x...>>> map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81]
Reduce function
Reduce functions a function in a sequence [X1, x2, x3 ...] , the function must receive two parameters, and reduce calculates the result and the next element of the sequence, and the effect is:
Reduce (f, [X1, x2, X3, x4]) = f (f (f (x1, x2), x3), x4)
For example, to sum a sequence, it can be implemented with reduce:
>>> def add (x, y): ... return x + y...>>> reduce (add, [1, 3, 5, 7, 9]) 25
Filter function
Python's built-in filter () function is used for filtering sequences. Like map (), filter () also receives a function and a sequence. When different from map (), filter () applies the incoming function to each element sequentially, and then decides whether to persist or discard the element based on whether the return value is true or false.
True reserved, false discarded
For example, in a list, delete even numbers, keep only odd numbers, and you can write:
def is_odd (n): return n% 2 = = 1filter (is_odd, [1, 2, 4, 5, 6, 9, 10, 15]) # results: [1, 5, 9, 15]
The key is to implement a "filter" function correctly by using the filter () as a high-order function.
PYTHON:LAMBDA, filter, map, reduce