All pairwise means between elements of 2 lists

Question:

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?

Asked By: db_

||

Answers:

What I feel is you could use only one for loop to make things pretty clean. By using the zip() function you could make the code easier. One of the best approaches with the least time complexity O(logn) would be:

import numpy as np
A = [1,2,3]
B = [8,12,11]
C = [np.mean([x,y]) for x,y in zip(A,B)] # List Comprehension to decrease lines
print(C)
Answered By: The Myth

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

I propose a list comprehension like this:

C= [[(xx+yy)/2 for yy in B] for xx in A]
Answered By: msi_gerva
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. ]])
Answered By: Chrysophylaxs
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.