gpt4 book ai didi

Python - 修改与覆盖对象引用

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:11 25 4
gpt4 key购买 nike

有人可以用一种易于理解的方式解释修改与覆盖对象引用吗?这是我的意思的一个例子:

通过修改对象引用:

nested_list = [[]]*3
nested

result:
[[], [], []]
# now let me **modify** the object reference
nested[1].append('zzz')

result:
[['zzz'], ['zzz'], ['zzz']]

通过覆盖对象引用:

nested_list = [[]]*3
nested

result:
[[], [], []]
# now let me **modify** the object reference
nested[1] = ['zzz']

result:
[[], ['zzz'], []]

这是否意味着在使用“追加”时我们只是在使用赋值时修改对象引用,即

nested[1] = ['zzz']

我们正在覆盖值并将 nested[1] 分配给新的对象引用?它是由“附加”方法和赋值之间的潜在差异引起的吗?如果有,有什么区别?

最佳答案

让我们将名称 x 分配给一个空列表,以便更容易对代码进行推理。

在你的第一个例子中

>>> x = []
>>> nested = [x]*3
>>> nested
[[], [], []]

您正在创建一个 嵌套 列表,其中包含对 x 的三个引用。证明如下:

>>> all(e is x for e in nested)
True

我们只创建了一个空列表x,这就是为什么

nested[0].append('zzz')
nested[1].append('zzz')
nested[2].append('zzz')

x.append('zzz')

都是等价的并将附加到内存中的相同列表:

>>> nested[0].append('zzz')
>>> nested
[['zzz'], ['zzz'], ['zzz']]
>>> nested[1].append('zzz')
>>> nested
[['zzz', 'zzz'], ['zzz', 'zzz'], ['zzz', 'zzz']]
>>> nested[2].append('zzz')
>>> nested
[['zzz', 'zzz', 'zzz'], ['zzz', 'zzz', 'zzz'], ['zzz', 'zzz', 'zzz']]
>>> x.append('zzz')
>>> nested
[['zzz', 'zzz', 'zzz', 'zzz'], ['zzz', 'zzz', 'zzz', 'zzz'], ['zzz', 'zzz', 'zzz', 'zzz']]

第二个例子很简单。您创建了一个 nested 列表,它最初包含对同一个空列表的三个引用。

然后您覆盖nested(即nested[1])的第二个元素通过发出

>>> x = []
>>> nested = [x]*3
>>> nested[1] = ['zzz']
>>> nested
[[], ['zzz'], []]

nested的第二个元素是一个新列表,与nested的第一个和第三个元素无关。

>>> nested[0] is nested[1]
False
>>> nested[2] is nested[1]
False
>>> nested[0] is nested[2]
True

由于您没有修改 nested[0]nested[2] 引用,它们仍然持有相同的空列表(在我们的示例中也通过名称 x)。

>>> x.append('x')
>>> nested
[['x'], ['zzz'], ['x']]

关于Python - 修改与覆盖对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43965902/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com