How to sum the values of an index?

0

I'm new to python and need to do a program that adds the digits that belong to the same position in a list, for example:

Lista = ['22659', '387685', '89546']

The result of the sum of the list [0] would be 24 (2 + 2 + 6 + 5 + 9), putting all the sums in another list would be:

resultado = ['24', '37', '32']

The code I have for now only separates the digits one by one, but I do not know if this is the best way to solve the problem:

for x in lista:
   for k in x:
      print(k)
    
asked by anonymous 20.09.2017 / 20:15

1 answer

1

The simplest way to do it is very similar to what you have now:

lista = ['22659', '387685', '89546']

resultado = []
for sequencia in lista:
    soma = 0
    for valor in sequencia:
        soma = soma + int(valor)
    resultado.append(soma)

print(resultado)

The only thing is that you will need to have a control variable soma , which will be the sum of the digits and remember to always convert the character to int .

  

See working at Ideone .

Advancing a little at the code level, you can use list comprehension as an alternative to calculate the sum of the digits:

lista = ['22659', '387685', '89546']

resultado = []

for sequencia in lista:
    soma = sum(int(valor) for valor in sequencia)
    resultado.append(soma)

print(resultado)

See the line:

soma = sum(int(valor) for valor in sequencia)

Replaces the second for with integer. They are, for practical purposes, equivalent.

  

See working at Ideone .

And if you still want to improve the code, you can replace the for that runs through the list with a call to the map function, since the goal of for is to generate a new list based on the original values. Semantically, you will be mapping the list, so you can do:

lista = ['22659', '387685', '89546']

resultado = map(lambda sequencia: sum(int(valor) for valor in sequencia), lista)

print(list(resultado))

In this case, the return of the map function will be a generator , so to display all the result you need to convert to list with list .

  

See working at Ideone .

The three solutions generate the same results, but each has its own particularities. You are not expected to know or understand the three in the very beginning, but I hope it will serve as a study guide.

    
20.09.2017 / 20:41