2016-03-10 122 views
0

我想总结一个列表的元素,然后将每个总和的结果存储在另一个列表中。将列表的总和结果存储到另一个列表中?

到目前为止,我有这样的:

array1 = [1, 2, 3, 4]  
print(sum(int(i) for i in array1)) 

输出为10

但我想要做的是这样的:

input = [1, 2, 3, 4]  
output = [1, 3, 6, 10] 

我需要将值存储到每个步骤的第二个列表中?

回答

0

这你想要做什么,但也许不是那么好懂......

output = [sum(array1[:i+1]) for i in range(len(array1))] 

你也可以做这样的(这应该是更容易理解):

i = 0 
output = [] 
for item in array1: 
    i += item 
    output.append(i) 
1

使用列表理解可能不是最简单的方法。你可以这样做:

input = [1, 2, 3, 4] 
output = [] 
total = 0 
for i in input: 
    total += i 
    output.append(total) 
+0

感谢,所以这里的交易是将每个结果附加到一个新数组(总数)中,现在非常清楚。 –

2

如果你正在运行的Python 3.2或更高版本,已经有这个功能,itertools.accumulate

import itertools 

input = [1,2,3,4] 

output = list(itertools.accumulate(input)) 

如果您使用的是3.2以前的版本Python中,你可以随时借用accumulate文档中提供的等效代码:

def accumulate(iterable, func=operator.add): 
    'Return running totals' 
    # accumulate([1,2,3,4,5]) --> 1 3 6 10 15 
    # accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120 
    it = iter(iterable) 
    try: 
     total = next(it) 
    except StopIteration: 
     return 
    yield total 
    for element in it: 
     total = func(total, element) 
     yield total 
+0

不知道,谢谢! – Felix

0

,如果你正在做的很多,如果数字运算你可能numpy的有用的cumsum法会做你想要的这里:

In [11]: import numpy as np 

In [12]: array1 = np.array([1, 2, 3, 4]) 

In [13]: array1.cumsum() 
Out[13]: array([ 1, 3, 6, 10]) 

这是很容易使用Python应用相同的逻辑:

def cumsum(l): 
    it = iter(l) 
    sm = next(it, 0) 
    yield sm 
    for i in it: 
     sm += i 
     yield sm 

演示:

In [16]: array1 = [1, 2, 3, 4] 

In [17]: list(cumsum(array1)) 
Out[17]: [1, 3, 6, 10] 
相关问题