首页 > 解决方案 > numpy:数组数组乘以整数数组等于数组

问题描述

有没有一种 Pythonic 的方法来计算数组z而不使用循环?

import numpy as np

x = np.array([[1, 2, 3], [6, 7, 8]])
y = np.array([5, 8])
z = np.array([x[i] * y[i] for i in range(0, len(x))])

标签: pythonnumpy

解决方案


你可以做:

x * np.expand_dims(y, 1)

乘以(shape 2×3)时,乘法将根据需要广播expand_dims(shape 2×1)的结果x

结果:

array([[ 5, 10, 15],
       [48, 56, 64]])

推荐阅读