Python - 递归和列表

2022-01-09 00:00:00 python 递归 list sum

问题描述

如何使用 Python 生成一个列表,其中每个元素都是前面数字的总和.

How to generate a list with Python in which each element is the sum of the previous numbers.

这是一个例子:

input: [ 25690.16, -34010.61, 9278.44, -808.00, -2126.95, 3920.19, -1793.23, 997.54, -1142.55, -69349.58 ]

25690.16 + -34010.61 = -8320.45
-8320.45 + 9278.44 = -8320.45
957.99 + -808.00 = 149.99
149.99 + -2126.95 = -1976.96
-1976.96 + 3920.19 = 1943.23
1943.23 + -1793.23 = 150
150 + 997.54 = 1147.54
1147.54 + -1142.55 = 4.99
4.99 + -69349.58 = -69344.54

output: [ 25690.16, -8320.45, -8320.45, 149.99, -1976.96, 1943.23, 150, 1147.54, 4.99, -69344.54 ]


解决方案

使用itertools.accumulate

>>> from itertools import accumulate
>>> l = [ 25690.16, -34010.61, 9278.44, -808.00, -2126.95, 3920.19, -1793.23, 997.54, -1142.55, -69349.58 ]
>>> list(accumulate(l))
[25690.16, -8320.45, 957.9899999999998, 149.98999999999978, -1976.96, 1943.23, 150.0, 1147.54, 4.990000000000009, -69344.59]

这通常比 numpy.cumsum

>>> from numpy import cumsum
>>> l = [ 25690.16, -34010.61, 9278.44, -808.00, -2126.95, 3920.19, -1793.23, 997.54, -1142.55, -69349.58 ]
>>> cumsum(l)
array([  2.56901600e+04,  -8.32045000e+03,   9.57990000e+02,
         1.49990000e+02,  -1.97696000e+03,   1.94323000e+03,
         1.50000000e+02,   1.14754000e+03,   4.99000000e+00,
        -6.93445900e+04])

相关文章