Python:理解引用

标签 python numpy

我理解基本的 python 引用,例如 a+=b 和 a=a+b 之间的区别,但这让我感到困惑。

import numpy as np
arr1 = np.arange(6).reshape(2,3)
arr2 = arr1[0]
arr2 is arr1[0] #returns False, when I expect True
arr1[0] = [7,8,9]
arr2 #[7,8,9], when I expect [0,1,2] since the 'is' returned False

这是怎么回事?

最佳答案

当你索引 numpy 数组时,你创建了一个新 View (它本身就是一个 numpy 数组)。这是一个不同的对象,因此 is 失败,但它是同一 block 硬件内存的 View 。因此,当您修改该 View 时,您修改了可能存在另一个 View 的那部分内存。

编辑:您实际上可以通过检查数组的 ctypes.data 属性来查看与 numpy 数组关联的内存的起始地址。

In [1]: import numpy as np

In [2]: arr1 = np.arange(6).reshape(2,3)

In [3]: arr2 = arr1[0]

In [4]: arr2.ctypes.data
Out[4]: 39390224

In [5]: arr1[0].ctypes.data
Out[5]: 39390224

一样!

关于Python:理解引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16675351/

相关文章:

python - 在 Python 中更改函数的关键字默认值

python - pybind11 与 numpy 的矩阵乘积

python - 处理溢出错误: math range error in Python with NumPy

python - 是否有更好的函数来查找公共(public)节点列表上的边?

python - sys.argv 无输出

python - 在 Python 中获取 XML 属性值列表

python - 如何从列表中将五个元素组成一组?

Python:为什么 MRO 中的最后一个类在其 super 的 __init__ 调用中应该有零参数,否则会出现运行时异常

macos - Python 2.7 - 升级到 El Capitan 后无法升级/安装某些软件包

python - 在numpy中为LUT创建渐变图像(查找表)