Home > Software engineering >  All pairwise means between elements of 2 lists
All pairwise means between elements of 2 lists

Time:11-02

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?

CodePudding user response:

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.array(A).reshape(-1, 1)   B) / 2 # Here B will be implicitly converted to a numpy array. Thanks to @Jérôme Richard.

CodePudding user response:

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)

CodePudding user response:

I propose a list comprehension like this:

C= [[(xx yy)/2 for yy in B] for xx in A]

CodePudding user response:

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. ]])
  • Related