'sum of a int in a list excluding the " " python

I have a list like this

lst = [12, 0, 13, ' ', 8, ' ', 13, 4, 4, 3, ' ', 0, ' ', 19, 0, 23, 8, ' ', 20, 15, ' ', 19, 14, ' ', 20, 1, 20, 3]

and what I am looking to have is something like this:

lst = [25, 8, 24, 0, 50, 35, 33, 44]

basically, the sum of the integer between the ' ' and removing the ' ', can someone can help me out



Solution 1:[1]

Solution with itertools.groupby (lst is your list from the question):

from itertools import groupby

out = [sum(g) for t, g in groupby(lst, type) if t is not str]
print(out)

Prints:

[25, 8, 24, 0, 50, 35, 33, 44]

Solution 2:[2]

I would make a new list for the sums and track an index counter. Increment through the original list and collect the sum up until you reach a non-integer, then increment your index (and also append a fresh 0 to the sums list).

list = [12, 0, 13, ' ', 8, ' ', 13, 4, 4, 3, ' ', 0, ' ', 19, 0, 23, 8, ' ', 20, 15, ' ', 19, 14, ' ', 20, 1, 20, 3]

sums = [0]
index = 0
for n in list:
    if isinstance(n, int):
        sums[index] += n
    else:
        sums.append(0)
        index += 1

print(sums)

Output:

[25, 8, 24, 0, 50, 35, 33, 44]

Solution 3:[3]

Yuck, that's a really awful data format. I suspect the best way to deal with it is just with a straightforward loop:

lst = [12, 0, 13, ' ', 8, ' ', 13, 4, 4, 3, ' ', 0, ' ', 19,
       0, 23, 8, ' ', 20, 15, ' ', 19, 14, ' ', 20, 1, 20, 3]

results = []
partial_sum = 0

for x in lst:
    if x == " ":
        results.append(partial_sum)
        partial_sum = 0
    else:
        partial_sum += x

results.append(partial_sum)    # handle the final sum at the end

Solution 4:[4]

here is another way:

res = []
sum = 0
for num in list:
    if num == ' ':
        res.append(sum)
        sum = 0
    else :
        sum +=num
if list[-1] != ' ': res.append(sum)
print(res)

output

>>> [25, 8, 24, 0, 50, 35, 33]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 notoriousjere
Solution 3
Solution 4