我偶尔会看到Python代码中使用的列表切片语法,如下所示:
newList = oldList[:]
当然这与以下相同:
newList = oldList
或者我错过了什么?
[:]
Shallow复制列表,制作包含对原始列表成员的引用的列表结构的副本.这意味着副本上的操作不会影响原始结构.但是,如果您对列表成员执行某些操作,则两个列表仍会引用它们,因此如果通过原始组件访问成员,则会显示更新.
一个深复制会使所有的成员的拷贝.
下面的代码片段显示了一个浅层副本.
# ================================================================ # === ShallowCopy.py ============================================= # ================================================================ # class Foo: def __init__(self, data): self._data = data aa = Foo ('aaa') bb = Foo ('bbb') # The initial list has two elements containing 'aaa' and 'bbb' OldList = [aa,bb] print OldList[0]._data # The shallow copy makes a new list pointing to the old elements NewList = OldList[:] print NewList[0]._data # Updating one of the elements through the new list sees the # change reflected when you access that element through the # old list. NewList[0]._data = 'xxx' print OldList[0]._data # Updating the new list to point to something new is not reflected # in the old list. NewList[0] = Foo ('ccc') print NewList[0]._data print OldList[0]._data
在python shell中运行它会得到以下脚本.我们可以看到使用旧对象的副本制作的列表.其中一个对象可以通过旧列表引用更新其状态,并且可以在通过旧列表访问对象时看到更新.最后,可以看到更改新列表中的引用不会反映在旧列表中,因为新列表现在指的是不同的对象.
>>> # ================================================================ ... # === ShallowCopy.py ============================================= ... # ================================================================ ... # ... class Foo: ... def __init__(self, data): ... self._data = data ... >>> aa = Foo ('aaa') >>> bb = Foo ('bbb') >>> >>> # The initial list has two elements containing 'aaa' and 'bbb' ... OldList = [aa,bb] >>> print OldList[0]._data aaa >>> >>> # The shallow copy makes a new list pointing to the old elements ... NewList = OldList[:] >>> print NewList[0]._data aaa >>> >>> # Updating one of the elements through the new list sees the ... # change reflected when you access that element through the ... # old list. ... NewList[0]._data = 'xxx' >>> print OldList[0]._data xxx >>> >>> # Updating the new list to point to something new is not reflected ... # in the old list. ... NewList[0] = Foo ('ccc') >>> print NewList[0]._data ccc >>> print OldList[0]._data xxx
就像NXC所说的那样,Python变量名实际上指的是一个对象,而不是内存中的特定位置.
newList = oldList
会创建指向同一对象的两个不同变量,因此,更改oldList
也会发生变化newList
.
但是,当您这样做时newList = oldList[:]
,它会"切片"列表,并创建一个新列表.默认值为[:]
0和列表的结尾,因此它会复制所有内容.因此,它会创建一个新列表,其中包含第一个中包含的所有数据,但两者都可以在不更改另一个的情况下进行更改.
至于已经回答,我只需添加一个简单的演示:
>>> a = [1, 2, 3, 4] >>> b = a >>> c = a[:] >>> b[2] = 10 >>> c[3] = 20 >>> a [1, 2, 10, 4] >>> b [1, 2, 10, 4] >>> c [1, 2, 3, 20]