Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum elements of a list between zeros in Python

Tags:

python

list

I have a list:

lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]

And I need the sum of the elements between the 0s in a new list. I tried

lst1 = []
summ = 0
for i, elem in enumerate(lst):
    if elem != 0:
        summ = summ + elem
    else:
        lst1.append(summ)
        lst1.append(elem)
        summ = 0

but it returns [11, 0, 0, 0, 57, 0], while I expect [11, 0, 0, 57, 0, 8]

like image 563
Petr Petrov Avatar asked Jan 05 '23 00:01

Petr Petrov


1 Answers

Here's one way to this with itertools.groupby and a list comprehension. The grouping is done by checking if an element is zero, and if not zero, all items in the group are summed:

from itertools import groupby

lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]
f = lambda x: x==0
result = [i for k, g in groupby(lst, f) for i in (g if k else (sum(g),))]
print(result)
# [11, 0, 0, 57, 0, 8]

And of course, if items in your list are only numbers (to avoid generalising and introducing ambuigities), the lambda can be replaced with bool:

result = [i for k, g in groupby(lst, bool) for i in ((sum(g),) if k else g)]
like image 140
Moses Koledoye Avatar answered Jan 14 '23 07:01

Moses Koledoye