i was wondering if there is an easy way to do this:
a =
[[1,2],[3,4]]
b =
[[5,6],[7,8],[9,10]]
turning into this:
c =
[[[1,2], [1,2], [1,2]],
[[3,4], [3,4], [3,4]]]
d =
[[[5,6], [7,8], [9,10]],
[[5,6], [7,8], [9,10]]]
so i can do this:
c - d
i've already tried using np.meshgrid, but it was a really clunk:
indexes_b, indexes_a = np.meshgrid(
np.arange(a.shape[0]),
np.arange(b.shape[0])
)
c = a[indexes_a]
d = b[indexes_b]
c - d # works
CodePudding user response:
Use broadcasting
:
>>> a[:, None] - b
array([[[-4, -4],
[-6, -6],
[-8, -8]],
[[-2, -2],
[-4, -4],
[-6, -6]]])
>>> c - d
array([[[-4, -4],
[-6, -6],
[-8, -8]],
[[-2, -2],
[-4, -4],
[-6, -6]]])
CodePudding user response:
Try this:
a = [[1,2],[3,4]]
b = [[5,6],[7,8],[9,10]]
c = [[li]*len(b[0]) for li in a]
d = [[li]*len(a) for li in b]
print(c)
print(d)