1. Filter (more used)

Python2 was a built-in function, and Python3 changed to a built-in class.

The first argument is a function and the second argument is an iterable. The filter result is an object of type Filter, which is also an iterable.

ages = [12, 23, 30, 17, 16, 22, 19]
x = filter(lambda ele: ele > 18, ages)
adult = list(x)
print(adult)  # [23, 30, 22, 19]
Copy the code

2. Map (not used very much)

Map () is Python’s built-in higher-order function. It takes a function f and an iterable, and returns a new iterable by applying f to each element of the iterable in turn.

ages = [12, 23, 30, 17, 16, 22, 19]
m = map(lambda ele: ele + 2, ages)
print(list(m))  # [14, 25, 32, 19, 18, 24, 21]
Copy the code

3, reduce

In python3, if you want to use reduce, you need to import:

from functools import reduce
Copy the code

The reduce function accumulates the elements in the parameter sequence.

Definition of reduce function:

reduce(function, sequence [, initial] ) -> value
Copy the code

The function argument is a function with two arguments. Reduce takes one element from the sequence and the result of the last call to function as arguments.

For example, if we have the list LST =[1,2,3,4], we want to get the sum of each element of the list, as follows:

From functools import reduce LST =[1,2,3,4] print(reduce(lambda x,y: x+y, LST))Copy the code

What if we want the product of the sequence, the following code just means the product of each element of the list.

From functools import reduce LST =[1,2,3,4] print(reduce(lambda x,y: x*y, LST)) #Copy the code

Now, a little bit more complicated, notice what happens to lambda functions.

From functools import reduce LST =[1,2,3,4] print(reduce(lambda x,y: x*y+1, LST)) #1*2+1=3; #1*2+1=3; # 3*3+1=10 # the result of the above calculation is calculated with the third element of the list by the lambda function # 3*3+1=10 # Follow the analogy, you can add a few elements to demonstrate, or replace the lamDA function calculation, verify the results.Copy the code

Again, in the case of initialization values, instead of taking the first two items of the list, the initial value is the first, and the first element of the sequence is the second element, and the application calculation of lambda functions begins.

From functools import reduce LST =[1,2,3,4] print(reduce(lambda x,y: X + y, LST, 5)) # 5 is the initial value, can also be understood as the third parameter calculation process? -- -- > # 5 + 1 = 6 - > 6 + 2 = 8 8 + 3 = > 11 -- - > 11 + 4 = 15Copy the code