user1332577 user1332577 - 4 months ago 25
Python Question

Add current element in array + next element in array, iterating through array, python

What's the best way to go about adding the current element in an array to the next element in the array, then using that newly created element to add that to the next element of the array. For example, I have an array:

s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100]


I would like the end array to look like the following:

new_s=[50, 51.2658, 52.5003, 53.7408, 54.969, 56.1848, 100]


Thus leaving the max,min elements of the array unchanged. I started going this route:

arr_length=len(s)
new_s=[50]

for i, item in enumerate(s):
if i == 0:
new_s.append(new_s[i]+s[i+1])
elif 0<i<=(arr_length-2):
new_s.append(new_s[i]+s[i+1])


What am I doing wrong that isn't allowing me to keep the last item unchanged?

Currently I'm getting the following list:

new_s=[50, 51.2658, 52.5003, 53.7408, 54.969, 56.1848, 156.1848]

Answer

The beset way is using numpy.cumsum() for all of your items except the last one then append the last one to the result of cumsum():

>>> import numpy as np
>>> s=[50, 1.2658, 1.2345, 1.2405, 1.2282, 1.2158, 100]
>>> 
>>> np.append(np.cumsum(s[:-1]), s[-1])
array([  50.    ,   51.2658,   52.5003,   53.7408,   54.969 ,   56.1848,
        100.    ])

Or with python (3.X) use itertools.accumulate():

>>> import itertools as it
>>> 
>>> list(it.accumulate(s[:-1])) + s[-1:]
[50, 51.2658, 52.500299999999996, 53.74079999999999, 54.968999999999994, 56.184799999999996, 100]
Comments