-1

Say i have an array called my array

my_array= [[1,2],[1,3],[2,3]]

I want to add all the second element from each sub-list starting with 1 so that my output would be 5

Also using NumPy is not an option...

Does anyone know how to do this ?

cs95
  • 330,695
  • 80
  • 606
  • 657
z7med
  • 3
  • 1
  • 2

6 Answers6

5

You can use a conditional list comprehension for this.

my_array=[[1,2],[1,3],[2,3]]
my_sum=sum(v[1] for v in my_array if v[0]==1)

print(my_sum)

Output:

5
Neil
  • 13,713
  • 3
  • 27
  • 50
3

Use a list comprehension with a filter to select the items, then sum them:

result = sum([b for a,b in my_array if a == 1])
Mark Tolonen
  • 148,243
  • 22
  • 160
  • 229
1

You can loop over the arrays and check if the first element is 1, then add the second element to a variable:

result = 0
for i in range(0, len(my_array)):
    elem = my_array[i]
    if elem[0] == 1:
        result += elem[1]
Chris Witteveen
  • 495
  • 2
  • 7
0
my_array= [[1,2],[1,3],[2,3]]
sum = 0
for x in my_array:
    if x[0] == 1:
        sum+=x[1]

print(sum)
Van Peer
  • 2,057
  • 2
  • 22
  • 34
0

OP can't use numpy, but that does not have to be true for future readers of the question. Since we already have the non-numpy solutions covered, here's one with numpy.

>>> import numpy as np
>>> my_array = np.array([[1,2],[1,3],[2,3]])
>>>
>>> np.sum(my_array[:,1][my_array[:,0] == 1])
5
timgeb
  • 73,231
  • 20
  • 109
  • 138
0

For large data, converting to, or even better, using numpy from the beginning might be faster. Here, to_select is true if the corresponding element in to_sum is to be added:

my_array = numpy.array(my_array)
to select = my_array[:,0] == 1 
to_add = my_array[:,1]
result = numpy.sum(to_add[to_select])
ntg
  • 10,762
  • 7
  • 62
  • 81