24. 从二维数组a = np.array([[3,3,3],[4,4,4],[5,5,5]])中的每行减去一维数组b= np.array([1,2,3])中相应的值。
时间: 2023-12-30 11:03:07 浏览: 217
可以使用numpy库中的广播(broadcasting)机制来实现:
```python
import numpy as np
a = np.array([[3,3,3],[4,4,4],[5,5,5]])
b = np.array([1,2,3])
result = a - b.reshape(-1, 1)
print(result)
```
输出结果为:
```
[[2 2 2]
[2 2 2]
[2 2 2]]
```
其中,b.reshape(-1, 1)的作用是将一维数组b转化为列向量(3行1列),从而实现广播机制。将b与a进行相减时,b将被广播为3行3列的矩阵,然后再进行相减。
阅读全文
相关推荐














