简体   繁体   中英

2D Array Row Sum

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

Use map to iterate and create sum :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM