I have a (long) list in which zeros and ones appear at random:
list1 = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1]
1.I want to get another list
- the sum of the list up to where 0 appears
- where 0 appears, retain 0 in the list
list2 = [3, 0, 2, 0, 1, 0, 3]
It should work for corner cases as well like zeroes at start or end
list1 = [0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0]
list2 = [0, 3, 0, 2, 0, 1, 0, 3, 0]
Advertisement
Answer
You can use itertools.groupby
:
JavaScript
x
13
13
1
from itertools import groupby
2
3
list1 = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1]
4
5
out = []
6
for v, g in groupby(list1):
7
if v:
8
out.append(sum(g))
9
else:
10
out.extend(g) # or out.append(0) if you want to keep only single zero
11
12
print(out)
13
Prints:
JavaScript
1
2
1
[3, 0, 2, 0, 1, 0, 3]
2
For list1 = [0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0]
it prints:
JavaScript
1
2
1
[0, 3, 0, 2, 0, 1, 0, 3, 0]
2