Home > Backend Development > Python Tutorial > Introduction to the use of map function and reduce function in python (with code)

Introduction to the use of map function and reduce function in python (with code)

不言
Release: 2018-09-28 15:02:40
forward
3594 people have browsed it

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. .

map() function

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)
Copy after login

Display results:

 [1, 4, 9, 16, 25, 36, 49, 64, 81]
Copy after login

reduce() function

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)
Copy after login

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
Copy after login

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)
Copy after login

. 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
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template