最初の数字を同じに保ちながら、リスト内の連続する数字を合計しようとしています。
この場合、5 は 5 のまま、10 は 10 + 5 (15)、15 は 15 + 10 + 5 (30) になります。
x = [5,10,15]
y = []
for value in x:
y.append(...)
print y
[5,15,30]
必要ですitertools.accumulate()
(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
これは、反復可能で、遅延して効率的に完全に機能します。itertools
実装はより低いレベルで実装されるため、さらに高速になります。
リストとして使用する場合は、当然、list()
組み込みの: を使用しますlist(accumulate(x))
。
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])
私はPython 3.4を使用しています