Python functools.reduce解释

官方文档: #functools.reduce
源代码: Lib/functools.py

# 定义
import functools
functools.reduce(function, sequence[, initial]) -> value

官方解释:

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned.

意思就是,对一个 sequence 迭代地使用 function,将传入的 sequence reduce 到一个 value 的过程。

若给出了初始值 initial,则第一次调用 function 时传递的参数为 initial 和 sequence 的第一个元素,否则传递的参数为 sequence 的前两个元素,从第二次迭代开始每次传入前一次的计算结果和 sequence 的下一个元素。

比如上面官方给出的例子:

import functools
functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
>>>
15

function 为 x + y,sequence 为 [1, 2, 3, 4, 5],未给出 initial,所以:
第一次计算 (1 + 2)
第二次计算 ((1 + 2) + 3)

整个过程就是:((((1+2)+3)+4)+5) = 15。

给出了 initial 的例子:

import functools
a = functools.reduce(lambda x, y: x+y, [1, 2, 3, 4, 5], 20)
>>>
35

初始值为 20,所以计算过程为 (((((20+1)+2)+3)+4)+5) = 35。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不吃饭就会放大招

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值