Map
map (function, sequence)
map()The function receives two arguments, one is the function, the other is to function the Iterable map incoming function to each element of the sequence sequentially, and returns the result as a new one Iterator .
map()As a higher-order function, in fact it abstracts the arithmetic rules, so we can calculate not only the simple f (x) =x2, but also any complex function, for example, to convert all the list numbers to strings:
>>> list (map (str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))['1','2','3','4','5','6','7','8','9']
Filter
Filter (function, sequence)
Python's built-in filter() functions are used to filter the sequence.
and map() similar, filter() also receive a function and a sequence. And the map() difference is that the filter() incoming function acts on each element in turn, and then whether True False the element is persisted or discarded based on the return value.
def is_odd (n): return n% 2 = = 1list (filter (is_odd, [1, 2, 4, 5, 6, 9, ten,])# results: [1 , 5, 9, []
Different from the map
1 #Map2 3 deff (x):4 returnX *x5 6R = Map (f, [1, 2, 3, 4, 5, 6, 7, 8, 9])7 Print(List (r))8 9 #ResultsTen #[1, 4, 9, +, (+), +, +, Bayi] One A #Filter - - deff (x): the returnX *x - -R = Filter (f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) - Print(List (r)) + - #Results + #[1, 2, 3, 4, 5, 6, 7, 8, 9]
Python built-in functions