Skip to main content
 首页 » 编程设计

python之基于循环索引在 Python 中对列表求和

2025年05月04日13mengfanrong

我有一个包含数字的列表,我想对该列表的不同部分(按连续顺序)求和并将这些值存储在一个新列表中。

例子:

a = [0, 1, 2, 3, 4, 5] 
b = [] 
b.append(a[0]) 
b.append(a[0] + a[1]) 
b.append(a[0] + a[1] + a[2]) 

当然,我的列表要长得多,所以我假设我需要一个 for 循环,但我不确定如何继续。

请您参考如下方法:

您可以使用简单的 list comprehension , 与 slicing和 sum函数,像这样

>>> a = [0, 1, 2, 3, 4, 5] 
>>> [sum(a[:i + 1]) for i in xrange(len(a))] 
[0, 1, 3, 6, 10, 15] 

注意:正如 paxdiablo 和 DSM 指出的那样,这种方法效率非常低,因为它必须一次又一次地找到之前看到的所有数字的总和(例如,当您找到前 4 个元素的总和,您也将计算前三个元素的总和,以及隐式计算 2 个元素的总和)。因此,这不适合较大的列表。

解决此问题的最佳方法是将结果累加到一个临时变量中,然后像这样将其存储在列表中

>>> result, temp = [], 0 
>>> for item in a: 
...     temp += item 
...     result.append(temp) 
...      
>>> result 
[0, 1, 3, 6, 10, 15] 

实际上,如果您要迭代求和并且实际列表非常大,那么您最好将其设为 generator function。 , 像这样

>>> def accumulate_sum(input_list): 
...     temp = 0 
...     for item in input_list: 
...         temp += item 
...         yield temp 
...      

然后像这样逐个迭代获取值

>>> for item in accumulate_sum([0, 1, 2, 3, 4, 5]): 
...     print(item) 
...      
0 
1 
3 
6 
10 
15 

你也可以得到整个列表,用list函数,像这样

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

仅供引用,Python 3.2+ 有一个名为 itertools.accumulate 的函数, 可以这样使用

>>> from itertools import accumulate 
>>> from operator import add 
>>> a = [0, 1, 2, 3, 4, 5] 
>>> list(accumulate(a, func=add)) 
[0, 1, 3, 6, 10, 15] 

或者您可以传递自己的函数,将两个数字加到 accumulate 中,如下所示

>>> list(accumulate([0, 1, 2, 3, 4, 5], func=lambda x, y: x + y)) 
[0, 1, 3, 6, 10, 15]