Home > Article > Backend Development > Introduction to the use of map function and reduce function in python (with code)
This article brings you an introduction to the use of map function and reduce function in Python (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .
The map() function in Python receives two parameters, one is the calling function object (objects are everywhere in python, and the function can also be called as an object before it is instantiated) ), the other is the parameter required to call the function, and the return value is a list of the results calculated iteratively.
def func(x): return x*x r=map(func,[1,2,3,4,5,6,7,8,9]) l=list(r) print(l)
Display results:
[1, 4, 9, 16, 25, 36, 49, 64, 81]
The reduce function also requires two parameters, one is to call Function object, another number of parameters required to call the function, and its return value is to accumulate the calculation result with the next element.
from functools import reduce def add(x,y): print('x is:',x,'y is:',y) return x+y ret=reduce(add,[1,3,5,7,9]) print(ret)
Display results:
x is: 1 y is: 3 x is: 4 y is: 5 x is: 9 y is: 7 x is: 16 y is: 9 25
You may ask, python’s built-in functions You can get the desired result with sum(), why do you need reduce? Looking at the following case, we want to return [1,3,5,7,9] to 13579
from functools import reduce def add(x,y): print('x is:',x,'y is:',y) return x*10+y ret=reduce(add,[1,3,5,7,9]) print(ret)
. Display the result:
x is: 1 y is: 3 x is: 13 y is: 5 x is: 135 y is: 7 x is: 1357 y is: 9 13579
The above is the detailed content of Introduction to the use of map function and reduce function in python (with code). For more information, please follow other related articles on the PHP Chinese website!