Python列表切片语法没有明显的原因

2024-10-01 04:57:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我偶尔会看到Python代码中使用的列表切片语法如下:

newList = oldList[:]

当然这和:

newList = oldList

还是我遗漏了什么?


Tags: 代码列表语法切片遗漏newlistoldlist
3条回答

[:]Shallow copies列表,生成包含对原始列表成员的引用的列表结构的副本。这意味着对副本的操作不会影响原始文件的结构。但是,如果对列表成员执行某些操作,则两个列表仍然引用它们,因此,如果通过原始成员访问成员,则会显示更新。

一个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

既然已经得到了回答,我只需添加一个简单的演示:

>>> 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]

正如NXC所说,Python变量名实际上指向一个对象,而不是内存中的一个特定位置。

newList = oldList将创建指向同一对象的两个不同变量,因此,更改oldList也将更改newList

但是,当您执行newList = oldList[:]时,它会“切片”列表,并创建一个新列表。[:]的默认值是0和列表的结尾,因此它复制所有内容。因此,它创建了一个新列表,其中包含第一个列表中包含的所有数据,但这两个列表都可以在不更改另一个的情况下进行更改。

相关问题 更多 >