通常情况下,在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]
只有当右手边只有一个元素时,这个才会生效:
>>> 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)
为什么会这样?怎么可能不会出现错误?这种行为是否有文档记录,还是一个bug?