How can I sum a column of a list?

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

    You may be interested in numpy, which has more advanced array features. One of which is to easily sum a column:

    from numpy import array
    
    a = array([[1,2,3],
     [1,2,3]])
    
    column_idx = 1
    a[:, column_idx].sum() # ":" here refers to the whole array, no filtering.
    

提交回复
热议问题