繁体   English   中英

我试图了解参考在 python 中的工作原理

[英]I'm trying to understand how reference works in python

在第 7 行之后,我没有写过一行代码提到名为“outer”的列表。 但是,如果执行它,您会看到“外部”(即其中的嵌套列表)列表会由于第 10 和 12 行而更改/更新...

我猜它与参考与价值有关。 我的问题是,为什么第 13 行没有像第 7 行和第 10 行那样影响(更改/更新)“外部”列表? 我试图理解这个概念。 我怎么go一下呢。 我知道网上有很多资源……但我什至不知道用谷歌搜索什么。 请帮忙。

inner = []
outer = []

lis = ['a', 'b', 'c']

inner.append(lis[0])
outer.append(inner) <<---- Line 7 <<

print(outer)
inner.append(lis[1]) <<---- Line 10 <<
print(outer)
inner.append(lis[2]) <<---- Line 12 <<
print(outer)
lis[2] = 'x' <<---- Line *******13******* <<
print(outer)

这是您示例的简化版本:

some_list = []
a = 2

some_list.append(a)
a = 3

print(some_list)  # output: [2]
print(a)  # output: 3

如果我们按照您原来的逻辑,您会期望some_list在我们打印时包含值3 但现实是我们从未将a自身添加到列表中。 相反,编写some_list.append(a)意味着a引用的值附加到列表some_list

请记住,变量只是对值的引用 这是与上面相同的片段,但解释了什么引用了什么。

some_list = []  # the name "some_list" REFERENCES an empty list
a = 2  # the name "a" REFERENCES the integer value 2

some_list.append(a)  # we append the value REFERENCED BY "a" 
                     # (the integer 2) to the list REFERENCED 
                     # BY "some_list". That list is not empty
                     # anymore, holding the value [2]

a = 3  # the name "a" now REFERENCES the integer value 3. This
       # has no implications on the list REFERENCED BY "some_list".
       # We simply move the "arrow" that pointed the name "a" to
       # the value 2 to its new value of 3

print(some_list)  # output: [2]
print(a)  # output: 3

这里要理解的关键方面是变量只是对值的引用 some_list.append(a)并不是说“将变量a放入列表中”,而是“将此时变量a引用的值及时放入列表中”。 变量无法跟踪其他变量,只能跟踪它们所引用的值。

如果我们 append 第二次到some_list ,在修改a引用的值之后,这会变得更加清晰:

some_list = []
a = 2

some_list.append(a)
a = 3
some_list.append(a)

print(some_list)  # output: [2, 3]
print(a)  # output: 3

在 Python 中,当您将列表存储在变量中时,您不会存储列表本身,而是对计算机 RAM 中某处列表的引用。 如果你说

a = [0, 1, 2]
b = a
c = 3

那么ab都将引用同一个列表,因为您将b设置为a ,这是对列表的引用。 然后,修改a将修改b ,反之亦然。 然而, c是一个integer 它的工作方式不同。 就像那样:

  ┌───┐
a │ █━┿━━━━━━━━━━━━━━━┓ ┌───┬───┬───┐
  └───┘               ┠→│ 0 │ 1 │ 2 │
  ┌───┐               ┃ └───┴───┴───┘
b │ █━┿━━━━━━━━━━━━━━━┛
  └───┘
  ┌───┐
c │ 3 │
  └───┘

ab是对同一列表的引用,但c指向 integer 的指针,当您说d = c时,它被复制(整数)。 但是,不会复制对它的引用。

那么,让我们 go 回到你的程序。 当您说inner.append(lis[n])时,您将值添加到列表inner的末尾。 您不添加对列表列表中第 2 项的lis ,而是创建值本身的副本并将对该副本的引用添加到列表中! 如果您修改lis ,那么它只会对引用lis的变量产生影响。

如果您希望在修改lis时修改inner ,则将inner.append(lis[n])替换为 inner.append inner.append(lis)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM