I have this information:
[0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1]
and need add successively 15 only in the section between zeros, as result:
[0,15,30,45,60,75,0,15,30,45,0,15,30,45,60,0,15,30,45]
CodePudding user response:
import numpy
l = np.array([0,1,1,1,1,1,0,1,1,1,0,1,1,1,1,0,1,1,1])
l *= 15
s = np.hstack([np.cumsum(v) for v in np.split(l, np.where(l==0)[0])])
print(s)
np.split
takes an array to be split, and an iterable of cuts. np.where
gives you all of the indices i
where l[i] == 0
. np.cumsum
does the cumulative sum on all of these, and then np.hstack
puts them all back together.
CodePudding user response:
Pseudo code
create an empty list which will be the result
initialize a counter at 0
for each element of the original list
add 1 to the counter if the element is not 0 else reset the counter to 0
append to the result list 15 times the counter