0

Beginner at python here. I have been trying to figure out how to sum values from the same column but different rows. I've tried to search on how to do it but the thing is that I need only the value from a specific number of rows and not all of them.

List = [ [1,2,3,4],
         [1,2,3,4],
         [1,2,3,4],
         [1,2,3,4],
         [1,2,3,4]  ]

For example, how do I sum the values in column 2 from only row 0-2 (so in total 3+3+3), but not in row 3 or 4? Very grateful for any assistance!

0

5 Answers 5

2

List = [ [1,2,3,4],
         [1,2,3,4],
         [1,2,3,4],
         [1,2,3,4],
         [1,2,3,4]  ]

rows_to_sum = (0,1,2)
column = 2
_sum = 0

for each in rows_to_sum:
    _sum += List[each][column]

print(_sum)

Or, Using comprehension:

_sum = sum(List[each][column] for each in rows_to_sum)

Output: 9

Sign up to request clarification or add additional context in comments.

Comments

1

For this kind of matrix operations I recommend you to use numpy library.

With numpy you can easily split matrix[start_row:stop_row, start_col:stop_col].

import numpy as np 
l = np.array([[1,2,3,4],
             [1,2,3,4],
             [1,2,3,4],
             [1,2,3,4],
             [1,2,3,4]])

sum(l[0:3, 2])

Comments

1

Here is a simply function where you can declare the rows and the column of your list and get the sum of the values:

def sum_up(the_list, rows, col):
    return sum(the_list[i][col] for i in rows)

print(sum_up(List, (0,1,2), 2))
# 9

Comments

0

I think this should do this.

for i in List:
    sum = sum + i[3]

1 Comment

That sums across all rows, not a subset.
0

You can do this with list comprehension

sum([List[i][2] for i in range(3)])

or

sum([l[2] for l in List[:3]])

Although numpy provides much elegant and faster solution for larger arrays

l = np.array(List)
s = np.sum(l[:3, 2])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.