add the value of the items in the list

1

I am practicing an exercise in Python to add the elements of a list and when I add the values I get this way by console:

 [1, 2]
 1
 3
 [5, 4, 2]
 5
 9
 11
 [12, 11, 120]
 12
 23
 143
 [50, 22, 88, 80, 108]

and I want the total value of each list to come out and as you will see, I always repeat the first element in each result:

 [1, 2]
 1  <--- aca me agrega el 1 en consola 
 3  <--y yo lo que quiero es que solo me salga la suma que es 3 
 [5, 4, 2]
 5
 9

later I want to add the total value of all the elements, that's why I added it with lista2.append(suma) but when I add the values incorrectly I can not do well the total value of the sums.

    
asked by Alejandro Osama Se 02.10.2018 в 14:21
source

3 answers

0

The problem is in the print tab but you can do it in a simple way by adding the list and then adding the flattened list.

lista = [[1,2], [5,4,2], [12,11,120], [50,22, 88,80,108]]
for l in lista:
    print(l)  # <-- imprime la sublista
    print(sum(l)) # <-- la suma de la sublista

print(sum([elem for sublista in lista for elem in sublista])) # <-- imprime la suma de las listas

[1, 2]
3
[5, 4, 2]
11
[12, 11, 120]
143
[50, 22, 88, 80, 108]
348
505 # <-- la suma de todo
    
answered by 02.10.2018 в 15:14
0

To add everything you can use the sum() function, you can read about it in the documentation of Python .

Then:

lista1 = [ [1, 2], [5, 4, 2], [12, 11, 120] ]
for l in lista1:
    print(sum(l))

Luck

    
answered by 02.10.2018 в 14:44
0

The problem is in the tabulation. you just have to draw the value of the sum variable out of the loop and print the list above.

lista = [ [1, 2], [5, 4, 2], [12, 11, 120] ]
nume = 0

for i in lista:

    for m in i:
        nume += m
    print(i)    
    print(nume)

The output of the script is this.

    
answered by 02.10.2018 в 15:31