python - 获取列表部分的相应总和

标签 python list list-comprehension

我有一个列表 [0, 1, 2, 3, 4, 5, 6] 并对它的各个部分求和,以便:

l = [0, 1, 2, 3, 4, 5, 6] -> 21

l = [1, 2, 3, 4, 5, 6] -> 21

l = [2, 3, 4, 5, 6] -> 20

l = [3, 4, 5, 6] -> 18

l = [4, 5, 6] -> 15

l = [5, 6] -> 11

l = [6] -> 6

l = [] -> 0

因此,我得到了列表各部分的相应总和:[21, 21, 20, 18, 15, 11, 6, 0]

我使用的代码是:

[sum(l[i:]) for i in range(len(l) + 1)]

但是,对于范围大于 100000 的列表,代码会显着变慢。

知道为什么以及如何优化它吗?

最佳答案

我建议为此使用 itertools.accumulate(我 recallnp.cumsum 更快),通过一些列表反转以获得您想要的输出:

>>> from itertools import accumulate
>>> lst = [0, 1, 2, 3, 4, 5, 6]
>>> list(accumulate(reversed(lst)))[::-1]
[21, 21, 20, 18, 15, 11, 6]

(如果需要,您可以在末尾添加0)

关于python - 获取列表部分的相应总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56645826/

相关文章:

python - 添加到列表中的整数

list - Kotlin 将 List 转换为可变参数

Python - 展平字典列表

python - 列表理解的扩展导致列表幂集中的无限循环

Python - 使用 os.popen() 解析 Unix "ls"- 杀死子进程的问题

python - 为什么 KNeighborsClassifier 总是预测相同的数字?

Python - 打印出对特定实例的所有引用

python - 值错误: could not convert string to float:While loading data from sql server to Predict()

c# - 如何将字典转换为查找?

haskell - 为什么这个列表理解失败?