python学习之map函数和reduce函数的运用

MapReduce:面向大型集群的简化数据处理   引文

map()函数

Python中的map()函数接收两个参数,一个是调用函数对象(python中处处皆对象,函数未实例前也可以当对象一样调用),另一个是调用函数所需要的参数,返回值是迭代计算出的结果所组成的列表。

1 def func(x):
2     return x*x
3 r=map(func,[1,2,3,4,5,6,7,8,9])
4 l=list(r)
5 print(l)

显示结果:

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

reduce() 函数

reduce函数同样需要两个参数,一个是调用函数对象,另一个数调用函数所需要的参数,其返回值是将计算结果继续和下一个元素做累积。

1 from functools import reduce
2 def add(x,y):
3     print('x is:',x,'y is:',y)
4     return x+y
5 ret=reduce(add,[1,3,5,7,9])
6 print(ret)

显示结果:

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

或许可能会问,python的内置函数sum()就可以得到想要的结果,为什么要有reduce呢。看如下案例,我们想要将[1,3,5,7,9]返回成13579

1 from functools import reduce
2 def add(x,y):
3     print('x is:',x,'y is:',y)
4     return x*10+y
5 ret=reduce(add,[1,3,5,7,9])
6 print(ret)

显示结果:

1 x is: 1 y is: 3
2 x is: 13 y is: 5
3 x is: 135 y is: 7
4 x is: 1357 y is: 9
5 13579
原文地址:https://www.cnblogs.com/SunIan/p/9712924.html