gpt4 book ai didi

python - 为什么对看似数据副本的操作会修改原始数据?

转载 作者:太空狗 更新时间:2023-10-29 20:23:37 25 4
gpt4 key购买 nike

让我们引用 numpy 手册:https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing

Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool). There are two types of advanced indexing: integer and Boolean.

Advanced indexing always returns a copy of the data (contrast with basic slicing that returns a view).

然后对高级索引返回的内容进行操作永远不会修改原始数组。事实上:

import numpy as np

arr = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
indexes = np.array([3, 6, 4])

slicedArr = arr[indexes]
slicedArr *= 5
arr

这打印:

array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

然而,情况似乎并非总是如此。奇怪的是,如果我不将 [] 运算符返回的任何内容保存到中间变量,我就会以某种方式对原始数组进行操作。请考虑这个例子:

import numpy as np

arr = np.array([0, 10, 20, 30, 40, 50, 60, 70, 80, 90])
indexes = np.array([3, 6, 4])

arr[indexes] *= 5
arr

这打印:

array([  0,  10,  20, 150, 200,  50, 300,  70,  80,  90])

我不提示。实际上,这对我来说是救命稻草。然而,我不明白为什么这样做有效,我真的很想了解这一点。

据我所知,一旦我编写 arr[indexes],我就创建了数组的副本;所以随后的 *= 5 应该在这个副本上操作而不是在原始数组上。然而,这个计算的结果应该被丢弃,因为它没有写入任何变量。

但显然我错了。

我的误解在哪里?

最佳答案

While 语句

a = expr

a[x] = expr

看似相似,其实根本不同。第一个将名称“a”绑定(bind)到 expr。第二个或多或少是equivalenta.__setitem__(x, expr)__setitem__ 实际做什么取决于实现它的人,但常规语义是在 x 指示的位置更新容器对象 a 表达式。特别是,没有创建“表示 a[x]”的中间对象。

只是为了完整性 a[x] 如果它不在 l.h.s 上。语法上看起来像赋值的东西或多或少等同于 a.__getitem__(x)

更新 以响应后续问题(执行 a[x] *= 5 时会发生什么?)让我们检测相关方法,以便我们可以看看发生了什么。下面,__imul__ 是就地乘法“魔术方法”:

import numpy as np

class spy(np.ndarray):
def __getitem__(self, key):
print('getitem', key)
return super().__getitem__(key)
def __setitem__(self, key, value):
print('setitem', key)
return super().__setitem__(key, value)
def __imul__(self, other):
print('imul', other)
return super().__imul__(other)

a = spy((5, 5))
a[...] = 1
a[[1,2],[4,2]] *= 5

打印:

setitem Ellipsis
getitem ([1, 2], [4, 2])
imul 5
setitem ([1, 2], [4, 2])

关于python - 为什么对看似数据副本的操作会修改原始数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47850352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com