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 digits and remember to always convert the character to int
.
See working on Ideone.
Advancing a little in code level, you can use comprehensilist on as an alternative to calculate the sum of the figures:
lista = ['22659', '387685', '89546']
resultado = []
for sequencia in lista:
soma = sum(int(valor) for valor in sequencia)
resultado.append(soma)
print(resultado)
See that line:
soma = sum(int(valor) for valor in sequencia)
Replace the whole of the second for
. They, for practical purposes, are equivalent.
See working on Ideone.
And if you still want to improve the code, you can replace the for
who traverses the list by a call to the function map
, since the objective of for
is to generate a new list based on the original values. Semantically, you will be mapping the list, then 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 function return map
will be a Generator, then to display all the result you need to convert to list with list
.
See working on Ideone.
The three solutions generate the same results, but each has its own particularities. You’re not expected to know or understand all three of them right away, but I hope it serves as a study guide.
What sum would that be to get this result? Add each character of the string? And what code have you done?
– Woss
Possible duplicate of Calculate some digits of a number.
– Woss
Yes, it would add 2+2+6+5+9. The code I have so far only separates the digits one by one, but there is no distinction when the list[0] ends for the list [1]
– Dhonrian
If you think the question I mentioned does not solve the problem, edit your question and add your code. This will make it easier to identify your difficulty.
– Woss
I edited the question, maybe it’ll be easier to understand
– Dhonrian