[英]Numpy slicing vs list slicing
我的列表:
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
但在 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)
但:
p[0]=-1
p
>>array([-1,2,3,4,5])
l
>>array([-1,2,3,4,5])
尽管 numpy arrays 的第一个元素的 memory 地址不同, l
也在更新中。 谁能解释这背后的概念?
将id
称为 memory 地址有点牵强附会。 是的,在 CPython 中,它恰好是一个 memory 地址,但地址是什么? 碰巧,不是实际的数字数据,而是描述数字数据的 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.
如果id(A) == id(B)
,那么,例如, A.shape
不可能与B.shape
不同!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.