[英]Numpy slicing vs list slicing
My list:我的列表:
a=[1,2,3,4,5]
b=a[:]
id(a)
>>2181314756864
id(b)
>>2181314855232 (different as slicing creates a new object)
id(a[0])
>>140734633334432
id(b[0])
>>140734633334432 (same)
b[0]=-1
b
>>[-1,2,3,4,5]
a
>>[1,2,3,4,5] --perfectly fine
But in case of numpy:但在 numpy 的情况下:
import numpy as np
l=np.array([1,2,3,4,5])
p=l[:]
id(l)
>>2181315005136
id(p)
>>2181315019840 (different as it creates a new object, which is fine)
id(l[0])
>>2181314995440
id(p[0])
>>2181314995952 (different)
But:但:
p[0]=-1
p
>>array([-1,2,3,4,5])
l
>>array([-1,2,3,4,5])
Even though the memory addresses of first elements of numpy arrays are different, l
is also being updated.尽管 numpy arrays 的第一个元素的 memory 地址不同, l
也在更新中。 Can anyone explain the concept behind this?谁能解释这背后的概念?
Talking about id
as a memory address is a bit of a red herring.将id
称为 memory 地址有点牵强附会。 Yes, in CPython, it happens to be a memory address, but the address of what?是的,在 CPython 中,它恰好是一个 memory 地址,但地址是什么? Not , as it happens, the actual numeric data, but the Python object that describes the numeric data!碰巧,不是实际的数字数据,而是描述数字数据的 Python object!
Slicing in numpy creates a new Python object (hence a different id), but the new object shares the storage for the actual array with the old one. Slicing in numpy creates a new Python object (hence a different id), but the new object shares the storage for the actual array with the old one.
If id(A) == id(B)
, then, for example, A.shape
could not possibly be different from B.shape
!如果id(A) == id(B)
,那么,例如, A.shape
不可能与B.shape
不同!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.