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?
Advertisement
Answer
A = [1, 2, 3] B = [8, 12, 11] C = np.add.outer(A, B) / 2 # array([[4.5, 6.5, 6. ], # [5. , 7. , 6.5], # [5.5, 7.5, 7. ]])