How can I sum a column of a list?

后端 未结 8 937
慢半拍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:27

    Using a for loop (in a generator expression):

    data = [[1,2,3],
            [1,2,3]]
    
    column = 1
    print(sum(row[column] for row in data))  # -> 4
    
    0 讨论(0)
  • 2020-12-30 05:34

    You can use numpy:

    import numpy as np
    a = np.array([[1,2,3],[1,2,3]])
    a.sum(0)
    
    0 讨论(0)
提交回复
热议问题