The sum of the nested list without using the SUM function (exercise)

Trying to write a function that takes the sum of each list and returns individual values ​​in a new single list. For instance,

[[2, 7, 6], [9, 5, 1], [4, 3, 8]] 

becomes

[15, 15, 15]

What I still have:

def row_sums(square):
    total_list = []
    total = 0
    for i in square:
        for j in i: 
            total += j
        total_list.append(total)
    return total_list    

But it just accumulates each list on top of each other, resulting in:

[15, 30, 45] 

I am not sure how to save the amounts for each list separately. The SUM function is not allowed here because it is an exercise on nested loops.

Thank.

+4
source share
7 answers

You need to reset your counter totalbefore starting each of them. In addition, you do not need to declare it outside, because you will use it only inside.

def row_sums(square):
    total_list = []
    for i in square:
        total = 0
        for j in i: 
            total += j
        total_list.append(total)
    return total_list 
+3
source

, total . sum = 0 :

def row_sums(square):
    total_list = []
    for i in square:
        total = 0
        for j in i: 
            total += j
        total_list.append(total)
    return total_list  
+3

:

>>> list = [[2, 7, 6], [9, 5, 1], [4, 3, 8]] 
>>> import functools
>>> [functools.reduce(lambda x, y: x + y, sublist, 0) for sublist in list]
[15, 15, 15]

sum:)

functools.reduce .

: , [functools.reduce(int.__add__, sublist, 0) for sublist in list] ( , !)

+2

.

def row_sums(square):
    total_list = []
    total = 0
    for i in square:
       for j in i: 
          total += j
       total_list.append(total)
       total = 0
    return total_list
+1

, (, ):

def _notsum2(lists):
    per_yield = len(lists)
    total = 0
    for ind, next in enumerate(val for sublist in lists for val in sublist):
        if ind % per_yield == 0 and ind:
            yield total
            total = 0
        total += next
    yield total


if __name__ == '__main__':
    li = [[2, 7, 6], [9, 5, 1], [4, 3, 8]]
    print [g for g in _notsum2(li)]
0

map :

l=[[2, 7, 6], [9, 5, 1], [4, 3, 8]] 
a,b,c=[x for x in l]
map(lambda x,y,z:x+y+z, a,b,c)
-1

[sum(i) for i in zip(*[[2, 7, 6], [9, 5, 1], [4, 3, 8]])]

bultin zip func - ,

-2
source

Source: https://habr.com/ru/post/1650613/


All Articles