何为副本?何为视图?
副本:就是原有数据的一份拷贝。
视图:可理解为原有数据的一个别称或引用,通过该别称或引用亦便可访问、操作原有数据,但原有数据不会产生拷贝。
视图与副本的区别
副本即原有数据的一份拷贝,因此对副本的任何修改不会影响原有数据,同理,对原有数据的任何修改亦不影响副本数据。
视图仅是原有数据的一个引用或别称,通过视图修改数据可反映到对原有数据的修改,因此,在意图不明确的情况下需慎重操作。
出现副本的常见情况
列表切片;调用deepCopy()函数;调用Numpy中的copy()函数;等等。
出现视图的常见情况
Numpy中的赋值操作和切片操作,等等。
Python官方文档说明
- If we have a mutable object (
list
,dict
,set
, etc.), we can use some specific operations to mutate it and all the variables that refer to it will see the change. - If we have an immutable object (
str
,int
,tuple
, etc.), all the variables that refer to it will always see the same value, but operations that transform that value into a new value always return a new object.