How can I sum a column of a list?

后端 未结 8 1031
慢半拍i
慢半拍i 2020-12-30 04:31

I have a Python array, like so:

[[1,2,3],
 [1,2,3]]

I can add the row by doing sum(array[i]), how can I sum a column, using a

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 05:18

    [sum(row[i] for row in array) for i in range(len(array[0]))]
    

    That should do it. len(array[0]) is the number of columns, so i iterates through those. The generator expression row[i] for row in array goes through all of the rows and selects a single column, for each column number.

提交回复
热议问题