Search code examples
pythonarrayssum

How to print the sum of columns and rows in python?


I would like to print sum of each row and sum of each column of a two dimensional array, like this:

  • sum row1 = 123 (numbers are not real sums, just for example)
  • sum row2 = 123
  • sum row3 = 123

And the same with columns. I know how to do it in java, but dont know how to do it in python. This is my code(missing code for sums of rows and columns, because I dont know how to do it):

from random import randint

dim1 = input("Insert first dimension: ")
dim1 = int(dim1)

dim2 = input("Insert second dimension: ")
dim2 = int(dim2)

table1d = []

for i in range(dim1):
    table2d = []
    for j in range(dim2):
        table2d.append(randint(1, 170))
    table1d.append(table2d)
print(table1d)

totalSum = sum(map(sum, table1d))
print(totalSum)

sumRows = 0
for i in range(0, len(table1d), 1):
    sumRows += table1d[i]

Solution

  • For rows you need only

    sums_in_rows = list(map(sum, table1d))
    
    print(sums_in_rows)
    

    For columns it needs more

    sums_in_columns = [0]*len(table1d[0])  # create list for all results
    
    for row in table1d:
        for c, value in enumerate(row):
            sums_in_columns[c] += value
    
    print(sums_in_columns)
    

    You can also convert it to numpy array and then you have

    import numpy as np
    
    arr = np.array(table1d)
    
    print('rows:',  arr.sum(axis=1))
    print('cols:',  arr.sum(axis=0))
    print('total:', arr.sum())
    

    from random import randint
    
    dim1 = input("Insert first dimension: ")
    dim1 = int(dim1)
    
    dim2 = input("Insert second dimension: ")
    dim2 = int(dim2)
    
    table1d = []
    #x = 0
    for i in range(dim1):
        table2d = []
        for j in range(dim2):
            table2d.append(randint(1, 170))
            #table2d.append(x)
            #x += 1
        table1d.append(table2d)
    print(table1d)
    
    sums_in_rows = list(map(sum, table1d))
    print(sums_in_rows)
    
    sums_in_columns = [0]*len(table1d[0])
    for row in table1d:
        for c, value in enumerate(row):
            sums_in_columns[c] += value
    print(sums_in_columns)
    
    import numpy as np
    
    arr = np.array(table1d)
    print(arr.sum(axis=1))
    print(arr.sum(axis=0))
    print(arr.sum())