对列表中的连续数字求和。python

对列表中的连续数字求和。python,python,function,numbers,sum,Python,Function,Numbers,Sum,我试图对列表中的连续数字求和,同时保持第一个数字不变 在这种情况下,5将保持5,10将是10+5(15),15将是15+10+5(30) 您需要(在Python 3.2中添加)。不需要额外的东西,已经为您实现了 在Python的早期版本中,如果不存在,则可以使用以下纯Python实现: def accumulate(iterable, func=operator.add): 'Return running totals' # accumulate([1,2,3,4,5]) --&

我试图对列表中的连续数字求和,同时保持第一个数字不变

在这种情况下,5将保持5,10将是10+5(15),15将是15+10+5(30)

您需要(在Python 3.2中添加)。不需要额外的东西,已经为您实现了

在Python的早期版本中,如果不存在,则可以使用以下纯Python实现:

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)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total
这将完美地与任何iterable、Lazy和高效一起工作。
itertools
实现是在较低的级别上实现的,因此速度更快


如果您想将它作为一个列表,那么自然地只需使用
list()
内置的:
list(累积(x))

作为所有元素的总和,直到您所在的元素

x = [5,10,15]
y = [sum(x[:i+1]) for i in range(len(x))]
使用numpy.cumsum:

In[1]: import numpy as np
In[2]: x = [5,10,15]
In[3]: x = np.array(x)
In[4]: y = x.cumsum()
In[5]: y
Out[6]: array([ 5, 15, 30])

我使用的是Python3.4,这需要创建大量的子列表,并且只能处理序列,不能处理任意的可重用项。在3.2+中,它也在重塑方向盘。@draconisthory:注意这种方法的性能特征,因为当列表很长时,它会变得非常缓慢。它不仅创建
len(x)
子列表,而且每次对每个子列表求和,而不是将最新的值添加到运行的和中。Lattyware的答案是pythonic解决方案。不。这个是[[1],[1,2],[1,2,3],[1,2,3,4]。谢谢,你能更改已接受的答案吗?
x = [5,10,15]
y = [sum(x[:i+1]) for i in range(len(x))]
In[1]: import numpy as np
In[2]: x = [5,10,15]
In[3]: x = np.array(x)
In[4]: y = x.cumsum()
In[5]: y
Out[6]: array([ 5, 15, 30])