【发布时间】:2026-01-17 23:10:01
【问题描述】:
通常,如果您尝试在 numpy 中分配数组末尾之后,不存在的元素将被忽略。
>>> x = np.zeros(5)
>>> x[3:6] = np.arange(5)[2:5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (3) into shape (2)
但是,如果只分配了一个元素,则完全超出数组末尾的相同操作会“成功”:
>>> x[5:] = np.arange(5)[4:]
>>> x[5:] = np.arange(5)[4:100]
这只有在 RHS 有一个元素时才有效:
>>> x[5:] = np.arange(5)[3:]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not broadcast input array from shape (2) into shape (0)
为什么会这样?这里怎么可能不出错?这种行为是否记录在案,还是一个错误?
【问题讨论】:
标签: python numpy indexing slice