Python Forum

Full Version: Summing up rows and columns
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
result = [[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]]

qq = sum(result[3])
A. I can sum up all the rows using sum(). But how to sum the columns? Beside using the long method result[0][0]+result[1][0]+result[2][0]+result[3][0].

B. sum() will not work if one of the list elements is blank. Any way to resolve this?

Many thanks.

P/S

Found the answers. I should try harder n my search! Ha.

https://www.geeksforgeeks.org/python-col...sted-list/
You could transpose the rows into columns and then use sum
from itertools import zip_longest

rows = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

print(rows)


def transpose_rows(rows):
    return tuple(zip_longest(*rows, fillvalue=0))


columns = transpose_rows(rows)

print(columns)

print(sum(columns[3]))
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] ((1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15), (4, 8, 12, 16)) 40
(Aug-13-2021, 06:19 AM)Yoriz Wrote: [ -> ]You could transpose the rows into columns and then use sum
from itertools import zip_longest

rows = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

print(rows)


def transpose_rows(rows):
    return tuple(zip_longest(*rows, fillvalue=0))


columns = transpose_rows(rows)

print(columns)

print(sum(columns[3]))
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] ((1, 5, 9, 13), (2, 6, 10, 14), (3, 7, 11, 15), (4, 8, 12, 16)) 40
Noted. Good idea!
arr1 = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
arr2 = [list(col) for col in zip(*arr1)]
print(arr2)
print(sum(arr2[3]))
Output:
[[1, 5, 9, 13], [2, 6, 10, 14], [3, 7, 11, 15], [4, 8, 12, 16]] 40