How can I sum a column of a list?

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

    you can use zip():

    In [16]: lis=[[1,2,3],
       ....:  [1,2,3]]
    
    In [17]: map(sum,zip(*lis))
    Out[17]: [2, 4, 6]
    

    or with a simple for loops:

    In [25]: for i in xrange(len(lis[0])):
        summ=0
        for x in lis:
            summ+=x[i]
        print summ
       ....:     
    2
    4
    6
    

提交回复
热议问题