2D Array Row Sum

152 Views Asked by At

I have a 2D array in python and I'm trying to add the values in the rows, but I only get the sum from the last 1D array.

code:

def sum_row(A,n):
    for i in range(len(A)):
        s = 0
        for j in range(len(A[i])):
            s = A[i].sum()
    return s

expected result:

A =
 [[3 6 6 0 9 8]
 [4 7 0 0 7 1]
 [5 7 0 1 4 6]
 [2 9 9 9 9 1]]
sum of row 0 = 32
sum of row 1 = 19
sum of row 2 = 23
sum of row 3 = 39

results:

A = 
 [[3 6 6 0 9 8]
 [4 7 0 0 7 1]
 [5 7 0 1 4 6]
 [2 9 9 9 9 1]]
sum of row 0 = 39
sum of row 1 = 39
sum of row 2 = 39
sum of row 3 = 39
1

There are 1 best solutions below

0
TheMaster On

Use map to iterate and create sum:

a = [[1,1], [2,2]]
out = list(map(lambda row:sum(row) ,a))