Python 中的 reduce()(关键词:Python/reduce)

版权声明:本文为博主原创文章,可以转载,但转载前请联系博主。 https://blog.csdn.net/qq_33528613/article/details/81631486

Python 官方文档中的 reduce

廖雪峰 - Python 教程 中的 reduce 介绍

博客园网友的讲解,多了几个例子

reduce 把一个函数作用在一个序列 [x1, x2, x3...] 上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
>>> reduce(add, [1,2,3,4,5])
15
>>> reduce(lambda x, y: 10 * x + y, [1,2,3,4,5])
12345

Python 2 中的 reduce 可以直接拿来用;
Python 3 中的 reduce 在 funtools 中。

猜你喜欢

转载自blog.csdn.net/qq_33528613/article/details/81631486