![]() |
Summing up rows and columns - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Summing up rows and columns (/thread-34603.html) |
Summing up rows and columns - plumberpy - Aug-13-2021 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-column-wise-sum-of-nested-list/ RE: Summing up rows and columns - Yoriz - Aug-13-2021 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]))
RE: Summing up rows and columns - plumberpy - Aug-13-2021 (Aug-13-2021, 06:19 AM)Yoriz Wrote: You could transpose the rows into columns and then use sumNoted. Good idea! RE: Summing up rows and columns - naughtyCat - Aug-18-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]))
|