Skip to content
Advertisement

Compute cummulative sum until a zero appears

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

Prints:

JavaScript

For list1 = [0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0] it prints:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement