-1

I want to sum the 3rd and 4th rows in my list? I am looking for the easiest way to do that? I know it seems so easy, but I cannot find the similar examples, as I am thinking I don't use the right keywords!

[0.001, 0.017000000000000001, 4.0, 75.0]
[5352984.0, 23194715.0, 8.0, 150.0]
[2370914.0, 11533745.0, 21.0, 396.0]
[0.39500000000000002, 0.68100000000000005, 68.0, 1296.0]
[0.46400000000000002, 0.69099999999999995, 69.0, 1307.0]
[0.0, 0.001, 12.0, 226.0]
[0.0, 0.001, 10.0, 194.0]
[0.055, 0.22600000000000001, 7.0, 136.0]
[0.055, 0.109, 10.0, 181.0]
[0.001, 0.037999999999999999, 29.0, 556.0]
[0.0030000000000000001, 0.14099999999999999, 46.0, 873.0]
[0.0, 1.0, 15.0, 287.0]
[0.0, 0.0, 6.0, 108.0]
[0.0, 0.0, 29.0, 556.0]
[0.0, 0.024, 46.0, 873.0]
[7086684.0, 68448914.0, 3.0, 53.0]
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

1

Supposing that your list is like this:

this_list = [[0.001, 0.017000000000000001, 4.0, 75.0],
             [5352984.0, 23194715.0, 8.0, 150.0],
             [2370914.0, 11533745.0, 21.0, 396.0],
             [0.39500000000000002, 0.68100000000000005, 68.0, 1296.0],
             [0.46400000000000002, 0.69099999999999995, 69.0, 1307.0],
             [0.0, 0.001, 12.0, 226.0],
             [0.0, 0.001, 10.0, 194.0],
             [0.055, 0.22600000000000001, 7.0, 136.0],
             [0.055, 0.109, 10.0, 181.0],
             [0.001, 0.037999999999999999, 29.0, 556.0],
             [0.0030000000000000001, 0.14099999999999999, 46.0, 873.0],
             [0.0, 1.0, 15.0, 287.0],
             [0.0, 0.0, 6.0, 108.0],
             [0.0, 0.0, 29.0, 556.0],
             [0.0, 0.024, 46.0, 873.0],
             [7086684.0, 68448914.0, 3.0, 53.0]]

and your "3rd row" is this:

[ 4.,  8., 21., 68., 69., 12., 10.,  7., 10., 29., 46., 15.,  6., 29., 46.,  3.]

Then you can simply:

import numpy as np
np_list = np.array(this_list)
# sum in a new row
new_row = np.sum([np_list[:,2], np_list[:,3]], axis=0)

# sum each elements of the 3rd and 4rd rows separetadly
row3, row4 = np.sum([np_list[:,2], np_list[:,3]], axis=1)
martineau
  • 119,623
  • 25
  • 170
  • 301
Bruno Aquino
  • 103
  • 10
0

A function can be made for this.

def RowSum (gridlist,row):
        sumcount=0
        for sublist in gridlist: # iterates through every sublist
                   sumcount+=sublist[row-1]
        return sumcount

For your work of summation of row 3 and 4:

rsum= RowSum(gridlist,3)+RowSum(gridlist,4)
print(rsum)

Note that this function is designed keeping in mind that the row number starts from 1 and not from 0.

Thank You :)