如何以增量方式将列表中的数字相加,同时从最低值到最大值进行排序



>我正在尝试编写代码,首先,从低到高的顺序号(例如 1、3、2、4、5 到 1、2、3、4、5)。第二,我要逐步增加清单中的数字。例如。

1
3
6
10
15

我已经尝试使用 sum 函数,然后是 sorted 函数,但我想知道我是否可以将它们整齐地编写在代码中以解决所有问题。

Addition = [1, 13, 166, 3, 80, 6, 40]
print(sorted(Addition))

我能够水平排序数字,但我无法垂直添加数字。

显然,你需要一个cumulative addition.您可以使用简单的循环编写一个简单的代码,并随时随地yield结果

def cumulative_add(array):
    total = 0
    for item in array:
        total += item
        yield total

>>> list(cumulative_add([1,2,3,4,5]))
[1, 3, 6, 10, 15]

根据您的目标,您可能还希望使用一个库,例如 pandas ,它已经为您编写了累积总和。

例如

>>> s = pd.Series([1,2,3,4,5])
>>> s.cumsum()
0     1
1     3
2     6
3    10
4    15
您可以将

itertools.accumulatesorted一起使用:

import itertools
mylist = [1, 2, 3, 4, 5]
result = list(itertools.accumulate(sorted(mylist)))
# result: [1, 3, 6, 10, 15]

默认操作为 operator.add ,但您可以对其进行自定义。例如,如果需要,您可以运行产品而不是运行总和:

import itertools
import operator
mylist = [1, 2, 3, 4, 5]
result = list(itertools.accumulate(sorted(mylist), operator.mul))
# result: [1, 2, 6, 24, 120]