对 Numpy 数组进行切片始终返回数组的视图(引用)。修改切片将修改原始数组。
在第二个示例中,您重新分配给名称s
。这不会修改对象。 Anew创建数组来表示结果s // 2
- 其中有与 没有关系原本的arr
- 进而s
成为该新数组的名称。
修改s
就地,使用增强赋值运算符,例如//=
,或者(正如您已经看到的)切片分配,例如[:]
:
>>> import numpy as np
>>> arr = np.arange(10)
>>> s = arr[2:5]
>>> s, arr
(array([2, 3, 4]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
>>> s[:] = 12 # modifies the slice, and therefore the original
>>> s, arr
(array([12, 12, 12]), array([ 0, 1, 12, 12, 12, 5, 6, 7, 8, 9]))
>>> s //= 2 # modifies the slice, and therefore the original
>>> s, arr
(array([6, 6, 6]), array([0, 1, 6, 6, 6, 5, 6, 7, 8, 9]))
>>> s = s // 2 # makes a new slice (and reassigns the name), so the original is untouched
>>> s, arr
(array([3, 3, 3]), array([0, 1, 6, 6, 6, 5, 6, 7, 8, 9]))