reduce将所有数据压缩到一起,得到一个最终的结果。

在python2中可以直接使用,在python3中需要导入

from functools import reduce

 自己实现代码:

1 num = [1,2,3,4,5,6,102]
2 def reduct_test(func,array):
3     res = array.pop(0)
4     for i in array:
5         res += func(i)
6     return res
7 
8 resource = reduct_test(lambda n:n,num)
9 print(resource)

得到结果:

123

 使用reduce方法

1 from functools import reduce
2 num = [1,2,3,4,5,6,102]
3 res = reduce(lambda n,y:n+y,num)
4 print(res)

得到结果:

123

 

posted on 2018-10-14 02:03  cherrydot  阅读(175)  评论(0编辑  收藏  举报