如何获取 reduce 的所有中间结果,以及最终结果?

2024-04-26 02:53:28 发布

您现在位置:Python中文网/ 问答频道 /正文

^{}的调用只返回最终结果:

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

不是自己写一个循环,而是存在一个返回中间值的函数吗?你知道吗

[3, 6, 10, 15]

(这只是一个简单的例子,我不想计算累积和-解决方案应该适用于任意af。)


Tags: lambda函数fromimportreduce解决方案例子functools
2条回答

您可以使用^{}

>>> from itertools import accumulate
>>> list(accumulate([1, 2, 3, 4, 5], lambda x, y: x+y))[1:]
[3, 6, 10, 15]

注意,参数的顺序是相对于functools.reduce()进行切换的。你知道吗

另外,默认的func(第二个参数)是一个和(比如operator.add),所以在您的例子中,它在技术上是可选的:

>>> list(accumulate([1, 2, 3, 4, 5]))[1:]  # default func: sum
[3, 6, 10, 15]

最后,值得注意的是,accumulate()将包含序列中的第一个项,因此,结果将从上面的[1:]索引。你知道吗


在你的编辑中,你注意到。。。你知道吗

This is only a simple example, I'm not trying to calculate the cumulative sum - the solution should work for arbitrary a and f.

关于accumulate()的好处是,它可以灵活地处理所需的可调用性。它只需要一个由两个参数组成的可调用函数。你知道吗

例如,builtin^{}满足:

>>> list(accumulate([1, 10, 4, 2, 17], max))
[1, 10, 10, 10, 17]

这是使用不必要lambda的一种较长形式:

>>> # Don't do this
>>> list(accumulate([1, 10, 4, 2, 17], lambda x, y: max(x, y)))
[1, 10, 10, 10, 17]
import numpy as np
x=[1, 2, 3, 4, 5]
y=np.cumsum(x) # gets you the cumulative sum
y=list(y[1:]) #  remove the first number
print(y)
#[3, 6, 10, 15]

相关问题 更多 >