Python - 递归和列表

时间:2022-11-10
本文介绍了Python - 递归和列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何使用 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])

这篇关于Python - 递归和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:存储为键值对的元组的总和值按键列出 下一篇:python素数之和

相关文章

最新文章