我偶尔会看到 Python 代码中使用的列表切片语法如下:
newList = oldList[:]
当然,这与以下内容相同:
newList = oldList
或者我错过了什么?
[:]
浅拷贝 http://en.wikipedia.org/wiki/Deep_copy#Shallow_copy列表,制作包含对原始列表成员的引用的列表结构的副本。这意味着对副本的操作不会影响原始的结构。但是,如果您对列表成员执行某些操作,两个列表仍会引用它们,因此如果通过原始成员访问成员,则会显示更新。
A 深拷贝 http://en.wikipedia.org/wiki/Deep_copy#Deep_copy也会复印所有名单成员。
下面的代码片段显示了正在运行的浅拷贝。
# ================================================================
# === 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)