Posts: 42 Threads: 13 Joined: Aug 2021 Aug-13-2021, 06:16 AM (This post was last modified: Aug-13-2021, 06:16 AM by plumberpy.) 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/ Posts: 2,167 Threads: 35 Joined: Sep 2016 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 Posts: 42 Threads: 13 Joined: Aug 2021 (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! Posts: 45 Threads: 0 Joined: Aug 2021 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 |