How can I sum a column of a list?

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

    I think the easiest way is this:

    sumcolumn=data.sum(axis=0)
    
    print (sumcolumn)
    
    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2020-12-30 05:16

    Try this:

    a = [[1,2,3],
         [1,2,3]]
    
    print [sum(x) for x in zip(*a)]
    

    zip function description

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 05:19

    You don't need a loop, use zip() to transpose the list, then take the desired column:

    sum(list(zip(*data)[i]))
    

    (Note in 2.x, zip() returns a list, so you don't need the list() call).

    Edit: The simplest solution to this problem, without using zip(), would probably be:

    column_sum = 0
    for row in data:
        column_sum += row[i]
    

    We just loop through the rows, taking the element and adding it to our total.

    This is, however, less efficient and rather pointless given we have built-in functions to do this for us. In general, use zip().

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题