鉴于以下代码,我希望最后两行的行为相同,但事实并非如此。
import numpy as np
C = np.matrix(np.zeros((4,4)))
C[0, 0:2] = np.matrix([[1, 2]]) # Works as expected.
C[0, [0,1]] = np.matrix([[1, 2]]) # Throws an "array is not broadcastable to correct shape" error.
相反,当使用 an 时ndarray
,事情会按预期工作(将分配的右侧调整为一维ndarray
):
D = np.zeros((4,4))
D[0, 0:2] = np.array([1, 2]) # Works as expected.
D[0, [0,1]] = np.array([1, 2]) # Works too.
更奇怪的是,如果一个人只是索引矩阵C
(而不是分配给它),似乎使用切片索引或列表只是返回相同的:
C[0, 0:2] # => matrix([[ 1., 2.]])
C[0, [0, 1]] # => matrix([[ 1., 2.]])
问题是,为什么这两种分配方法的行为不同?我错过了什么?
(编辑:错字)