正如我下面的 MWE 所示,调用 np.array(a, copy=False)
在现有阵列上 a
返回与预期完全一样的东西,除了 .data
属性好像不一样。怎么会这样?
>>> a # My original array
array([2])
>>> b = np.array(a, copy=False) # Not-a-copy of the original array
>>> b is a # The Python objects seem to be identical
True
>>> b.data is a.data # But their .data attributes aren't??
False
>>> a.data
<memory at 0x7f82ebd757c8>
>>> b.data
<memory at 0x7f82ebd75888>
>>> b
array([2])
>>> a
array([2])
>>> a[:] = 3 # Changing a indeed also changes b
>>> a
array([3])
>>> b
array([3])
>>> a.data
<memory at 0x7f82ebd757c8>
>>> b.data
<memory at 0x7f82ebd75888>
编辑
在玩的时候,我什至发现
.data
一边看一边属性变化!>>> a.data is a.data # a.data isn't equal to itself?!
False
>>> a.data
<memory at 0x7f82ebd75948>
>>> a.data
<memory at 0x7f82ebd75888> # A different value than a minute ago
>>> a.data
<memory at 0x7f82ebd75948>
>>> a.data
<memory at 0x7f82ebd75888>
>>> a.data
<memory at 0x7f82ebd75948>
>>> a.data
<memory at 0x7f82ebd75888>
>>> a.data
<memory at 0x7f82ebd75948>
>>> a.data
<memory at 0x7f82ebd75888>
>>> a.data
<memory at 0x7f82ebd75948>
最佳答案
如果您键入:
help(a.data)
您会看到它并没有完全返回您所期望的:
class memoryview(object)
| memoryview(object)
|
| Create a new memoryview object which references the given object.
|
| Methods defined here:
|
它创建了一个 的内存 View 。引用资料 那个物体。如果你想要内存地址使用
id
:id(a) == id(b)
True
注意:
id(a) is id(b)
False
因为
id(a)
也返回一个整数和 id(b) 以及它们的内存地址 不是 尽管它们的值是相同的。如果你想要十六进制内存:
hex(id(a))
此外,来自 NumPy 文档:numpy.ndarray.data (我真的不知道为什么这个
.data
有用但它存在)
关于python - 为什么不复制 numpy 数组会更改数据属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61102237/