Issue
Is there a function to all pairwise means (or sums, etc) of 2 lists in python?
I can write a nested loop to do this:
import numpy as np
A = [1,2,3]
B = [8,12,11]
C = np.empty((len(A),len(B)))
for i, x in enumerate(A):
for j, y in enumerate(B):
C[i][j] = np.mean([x,y])
result:
array([[4.5, 6.5, 6. ],
[5. , 7. , 6.5],
[5.5, 7.5, 7. ]])
but it feels like this is a very roundabout way to do this. I guess there is an option for a nested list comprehension as well, but that also seems ugly.
Is there a more pythonic solution?
Solution
Are you using numpy
? If so, you can broadcast your arrays and acheive this in one line.
import numpy as np
A = [1,2,3]
B = [8,12,11]
C = (np.reshape(A, (-1, 1)) + B) / 2 # Here B will be implicitly converted to a numpy array. Thanks to @Jérôme Richard.
Answered By - ILS
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.