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 ?
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
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])
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]
my_array= [[1,2],[1,3],[2,3]]
sum = 0
for x in my_array:
if x[0] == 1:
sum+=x[1]
print(sum)
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
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])