python中的内置高阶函数reduce

python中的内置高阶函数reduce

reduce():把一个函数作用在一个序列上,这个函数必须接收两个参数
reduce把结果继续和序列的下一个元素做累积计算

如:reduce(f,[1,2,3,4]) = f(f(f(1,2),3),4)

在python2和python3中高阶函数reduce区别:
python2:reduce是内置函数
python3:from functools import reduce

示例1:计算序列中x y累乘的结果

from functools import reduce

def multi(x,y):
    return x*y
print(reduce(multi,range(1,10)))

输出结果:

362880

示例2:计算序列中x y累加的结果

from functools import reduce

def add(x, y):
    return x + y
print(reduce(add, range(1, 101)))

输出结果:

5050
发布了60 篇原创文章 · 获赞 6 · 访问量 1340

猜你喜欢

转载自blog.csdn.net/weixin_45775963/article/details/103718342
今日推荐