Here's one way using numpy and a list comprehension:
In [23]: a = np.array([0,0,1,1,1,0,0,0,0,1,1,0,0])
In [24]: np.hstack([x.sum() if x[0] == 1 else x for x in np.split(a, np.where(np.diff(a) != 0)[0]+1)])
Out[24]: array([0, 0, 3, 0, 0, 0, 0, 2, 0, 0])
The logic:
- Find leading and trailing indices of where you have consequence 1s.
- Split your array from those indices
- sum those sub lists that have one and leave sub lists with zero the way they are
- flatten the result using
np.hstack.
If you want to replace the remained ones with 0 just do the following:
In [28]: np.hstack([[x.sum(), *[0]*(len(x) -1)] if x[0] == 1 else x for x in np.split(a, np.where(np.diff(a) != 0)[0]+1)])
Out[28]: array([0, 0, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0])
[0]*(len(x) -1) will create the expected 0s for you and using an in-place unpacking you'll be able to place them beside the sum(x).
If you ever wanted a pure Python approach here's one way using itertools.groupby:
In [63]: def summ_cons(li):
...: for k,g in groupby(li) :
...: if k:
...: s = sum(g)
...: yield s
...: yield from (0 for _ in range(s-1))
...: yield from g
...:
In [65]: list(summ_cons(a))
Out[65]: [0, 0, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0]