m、n阵列numpy m × n组合网格

dgiusagp  于 2023-02-04  发布在  其他
关注(0)|答案(2)|浏览(135)

我想知道是否有一个简单的方法来做到这一点:

a = 
[[1,2],[3,4]]

b =
[[5,6],[7,8],[9,10]]

变成了这样

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]]]

所以我可以这样做:

c - d

我已经尝试过使用np.meshgrid,但它确实很笨拙:

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
z0qdvdin

z0qdvdin1#

使用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]]])
nbysray5

nbysray52#

试试这个:

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)

相关问题