Home > Mobile >  sum of a int in a list excluding the " " python
sum of a int in a list excluding the " " python

Time:05-07

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

CodePudding user response:

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]

CodePudding user response:

here is another way:

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

output

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

CodePudding user response:

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]

CodePudding user response:

Try

l =[12, 0, 13, ' ', 8, ' ', 13, 4, 4, 3, ' ', 0, ' ', 19, 0, 23, 8, ' ', 20, 15, ' ', 19, 14, ' ', 20, 1, 20, 3]
valueToBeRemoved = " "
myList = [value for value in l if value != valueToBeRemoved]
print(myList)

Then you can sum it with

print(sum(myList))

CodePudding user response:

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

CodePudding user response:

Plenty of good solutions here already, maybe this code will be useful to you for another time:

test = [12, 0, 13, ' ', 8, ' ', 13, 4, 4, 3, ' ', 0, ' ', 19, 0, 23, 8, ' ', 20, 15, ' ', 19, 14, ' ', 20, 1, 20, 3]
list1 = map(str, test) 
res = []
for ele in list1:
    if ele.strip():
        res.append(ele)

res = [int(i) for i in res]
print('Length modified list: ', len(res))
print('Length original list: ', len(test))
  • Related