简体   繁体   中英

Sum of a matrix, even or odd

This function receives a numeric matrix represented as a list of rows, where each row is in turn a list. Assume that it is a square matrix: all rows have the same length and there are as many rows as elements in each row. Also assume that the matrix is at least of dimension 2 by 2 (ie minimally the matrix has 2 rows with 2 elements each) The function should return a list with as many elements as number of rows. Element i in the resulting list should have the sum of the values in row i.

For example, if the matrix is

1   2   3
10  20  30
100 200 300

then this function should return the list [6,60,600]

That is, addValuesInAllRows( [ [1,2,3], [10,20,30], [100,200,300] ] ) should return [6,60,600]

Isn't this sort of similar but how would you sum up the list individually

matrix = [ [1,2,3], [10,20,30], [100,200,300] ]
print [sum(row) for row in zip(*matrix)]

Sum of columns

>>> def addValuesInAllCols(arr):
      return [sum(x) for x in zip(*arr)]

>>> addValuesInAllCols( [ [1,2,3], [10,20,30], [100,200,300] ] )
[111, 222, 333]

Sum of rows

>>> map(sum, [ [1,2,3], [10,20,30], [100,200,300] ] )
[6, 60, 600]

One more option:

from operator import itemgetter

matrix = [ [1,2,3], [10,20,30], [100,200,300] ]

def addValuesInAllCols(arr):
    return map(sum, [map(itemgetter(i), arr) for i in range(len(a))])

Where map is a build-in function that can be rewritten as a simple for. For ex:

[map(itemgetter(i), arr) for i in range(len(a))] is the same as:

result = []
for i in range(len(a)):
    tmp = []
    for row in a:
        tmp.append(row[i])
    result.append(tmp)

Edited per new tests:

def addValuesInAllCols(arr):
    return map(sum, arr)

Or without map:

def addValuesInAllCols(arr):
    return [sum(row) for row in arr]

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