For some work that I am doing recently, I need the following operation to be done.
def myfunc(a, b):
return a*b # some operation here
a = [1,2,3]
b = [2,4,6,8]
print [[myfunc(i, j) for i in a] for j in b]
You can use numpy broadcasting:
a = np.array([1,2,3]) b = np.array([2,4,6,8]) a = a[:, None] b = b[None, :] a * np.log(a/b)
adding a new axis to
b (as second and first axis respectively) will make
(3, 1) and
(1, 4). Then,
a/b a 2D
(3, 4) array where the
i-th column is
a/b array([[ 0.5 , 0.25 , 0.16666667, 0.125 ], [ 1. , 0.5 , 0.33333333, 0.25 ], [ 1.5 , 0.75 , 0.5 , 0.375 ]])
Then you can take the pointwise log and multiply by
np.log(a/b) is (3, 4) and
a is (3, 1),
a will again be broadcasted to (3, 4).
A small subtlety is that, due to the way broadcasting happens, adding the second axis to
b is not mandatory. I prefer writing it out explicitly nevertheless, for clarity.