1.filter
Function: Filter is used to filter out elements that do not meet the function conditions. To delete or subtract elements from a sequence, use the filter function.
Format: filter (function, sequence)
Function can be an anonymous function or a custom function that returns True or False for each element of the following sequence, leaving the element True. A sequence can be a list, a tuple, or a string.
Note: Iterators require list conversions
Anonymous functions
import random allNum = [] for i in range(9): Append (random. Randint (1,20)) print(allNum) print(list(filter(lambda x:x%3,allNum))) # [8, 8, 9, 5, 4, 11, 19, 12, 1] # [8, 8, 5, 4, 11, 19, 1]Copy the code
Custom function
import random def fun(x): return x%2 allNum = [] for i in range(9): Append (random. Randint (1,20)) print(allNum) print(list(filter(fun,allNum))) #[12, 16, 6, 10, 7, 4, 4, 10, 17] #[7, 17]Copy the code
2.map
Function: Map is used to calculate the value of a sequence or multiple sequences after function mapping.
Format: the map (function, iterable1 iterable2)
Function can have one or more parameter values. The following iterable represents the parameter values in the function operation, passing in as many iterable values as possible.
Note: 1. Iterators need to perform list conversions. 2
Anonymous functions
X = y =,4,6,8,8 [3] [1, 2, 3, 4] print (list (map (lambda x, y (x * y) + 2, x, y))) # output: [34] 5, 10, 20,Copy the code
Custom function
X = y =,4,6,8,8 [3] [1, 2, 3, 4] def fun (x, y) : return (x * y) + 2 print (list (map (fun, x, y))) # output: [34] 5, 10, 20,Copy the code
3.reduce
Reduce is used to compress a sequence to obtain a value.
Format: reduce (function, iterable)
Two arguments must be passed to function, which can be a list or a tuple.
From functools import Reduce, map and filter are built-in functions, so they can be called directly.
Anonymous functions
From functools import reduce x=[3,4,6,8,8] print(lambda x,y: x+y)) #Copy the code
Custom function
From functools import reduce x=[3,4,6,8,8] def fun(x,y): return x+y print(reduce(fun,x)) #Copy the code
Calculation principle:
The first two elements are evaluated: f(3,4), which is 7.
Add the result to the third element,6: f(7,6) is 13;
Add the result to the fourth element 8: f(13,8) is 21;
Add the result to the fourth element 8: f(21,8) is 29;
After calculation, result 29 is returned.