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.