Python - 递归和列表

Python - recursive sum list(Python - 递归和列表)
本文介绍了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 - 递归和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reading *.mhd/*.raw format in python(在 python 中读取 *.mhd/*.raw 格式)
Count number of cells in the image(计算图像中的单元格数)
How to detect paragraphs in a text document image for a non-consistent text structure in Python OpenCV(如何在 Python OpenCV 中检测文本文档图像中的段落是否存在不一致的文本结构)
How to get the coordinates of the bounding box in YOLO object detection?(YOLO物体检测中如何获取边界框的坐标?)
Divide an image into 5x5 blocks in python and compute histogram for each block(在 python 中将图像划分为 5x5 块并计算每个块的直方图)
Extract cow number from image(从图像中提取奶牛编号)