Summarize list items between zeros in Python

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 0in the 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 returns [11, 0, 0, 0, 57, 0]while I expect [11, 0, 0, 57, 0, 8]

+4
source share
3 answers

Here is one way: itertools.groupbyand understanding the list. Grouping is performed by checking whether the element is equal to zero, and if it is not equal to zero, all elements 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 the items on your list are just numbers (to avoid generalizing and introducing ambuigities), lambdayou can replace it with bool:

result = [i for k, g in groupby(lst, bool) for i in ((sum(g),) if k else g)]
+7
source

, 0, 1

lst = [1, 2, 3, 5, 0, 0, 9, 45, 3, 0, 1, 7]
lst1 = []
summ = 0
for i, elem in enumerate(lst):
    if elem != 0:
        summ = summ + elem
    else:
        if summ:
            lst1.append(summ)
        lst1.append(elem)
        summ = 0

if summ:
    lst1.append(summ)
# lst1 = [11, 0, 0, 57, 0, 8]
+2

lst1.append(summ)

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

Source: https://habr.com/ru/post/1661848/


All Articles