How to add up the values of an index?

Asked

Viewed 948 times

1

I am new in python and need to make a program that add the digits that belong to the same position of a list, for example:

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

The result of the list sum[0] would be 24 (2+2+6+5+9), putting all 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 don’t know if it’s the best way to solve the problem:

for x in lista:
   for k in x:
      print(k)
  • What sum would that be to get this result? Add each character of the string? And what code have you done?

  • Possible duplicate of Calculate some digits of a number.

  • 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]

  • 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.

  • I edited the question, maybe it’ll be easier to understand

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 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.

  • That went very well. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.