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:
JavaScript
x
10
10
1
import numpy as np
2
3
A = [1,2,3]
4
B = [8,12,11]
5
6
C = np.empty((len(A),len(B)))
7
for i, x in enumerate(A):
8
for j, y in enumerate(B):
9
C[i][j] = np.mean([x,y])
10
result:
JavaScript
1
4
1
array([[4.5, 6.5, 6. ],
2
[5. , 7. , 6.5],
3
[5.5, 7.5, 7. ]])
4
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
JavaScript
1
7
1
A = [1, 2, 3]
2
B = [8, 12, 11]
3
C = np.add.outer(A, B) / 2
4
# array([[4.5, 6.5, 6. ],
5
# [5. , 7. , 6.5],
6
# [5.5, 7.5, 7. ]])
7