max2p
max2p

Reputation: 57

How to broadcast sum of list of list?

How to broadcast the sum of list of list in an efficient way? below is a working code, but its not quite efficient when list1 has nth value like 30 elements. Any improvement on this? from numpy import sum import numpy as np

list1 = [[4,8],[8,16]]
list2 = [2] 
elemSum=[sum(list1[0]),sum(list1[1])]
print((np.array(elemSum)/np.array(list2)))

prints:

[ 6. 12.] # expected output

I want a single line like this below , eliminating the declaration of variable elemSum, but it yields incorrect output since it sums 2 elements to 1

print(sum(np.array(list1)/np.array(list2)))

prints:

18.0 # not expected it sums 2 elements to 1

Upvotes: 0

Views: 480

Answers (2)

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 96172

Just use numpy the entire time, don't mess with lists if you want arrays:

list1 = [[4,8],[8,16]]
list2 = [2]
import numpy as np
arr1 = np.array(list1)
arr2 = np.array(list2)

Then simply:

result = arr1.sum(axis=1) / arr2

Upvotes: 1

Thomas
Thomas

Reputation: 182000

numpy.sum takes an optional axis argument, which can be used for partial sums along a single axis:

>>> list1 = np.array([[4,8],[8,16]])
>>> list2 = np.array([2])
>>> np.sum(list1)
36
>>> np.sum(list1, axis=1)
array([12, 24])
>>> np.sum(list1, axis=1) / list2
array([ 6., 12.])

Upvotes: 2

Related Questions