向列表中的列表附加一个值

huangapple go评论68阅读模式
英文:

Appending a value to a list inside a list

问题

以下是您要翻译的代码部分:

list = [1,2,3,4]
for x in [list] #Yes a list in a list:
    x.append(2)

print(x)
print(list)

翻译结果:

列表 = [1,2,3,4]
for x in [列表] #是的,一个列表在另一个列表中:
    x.append(2)

print(x)
print(列表)
英文:

A simple question regarding the appending rule of list.

So the code is

list = [1,2,3,4]
for x in [list] #Yes a list in a list:
    x.append(2)

print(x)
print(list)

The result of the two print is both [1,2,3,4,2]. I can see why print(x) outputs 1,2,3,4,2 but I didnt update the list yet but somehow the list is also updated.

Is there a hidden rule behind this? or is it just a default setting I need to memorize.

Thanks

Two prints have the same output and I wanna know why

答案1

得分: 1

在Python中,列表是按引用传递的,而不是按值传递的。
[list] 中的内部列表引用的是外部 list 中的相同列表。
因此,您进行的附加操作在两个引用中都可见(它们引用的是同一个列表)。

我制作了一个更简单的示例来说明同一点:

a = [1, 2, 3]
b = [a]
b[0].append(4)
print(a)
# 输出: [1, 2, 3, 4]
英文:

Lists in python are by reference, not by value.
inner list in [list] is referring to the same list as outside list
Therefore, the append you do is visible in both references (they are the same list).

I've made a simpler example that illustrates the same point:

a = [1, 2, 3]
b = [a]
b[0].append(4)
print(a)
>>> [1, 2, 3, 4]

答案2

得分: 0

这是类似于你的代码,我将其拆分以更好地解释:

sublist = [1,2,3,4]

sublist 是一个简单的一维数组。

li = [sublist] 

li 是一个包含 sublist 的列表,实际上是一个二维数组。

for x in li:

如果你迭代 lixli的每个元素,所以在最终迭代中,x 将是列表 [1,2,3,4]

x.append(2)

然后,你将2附加到 x,实际上是将其附加到 sublist

完整的代码如下:

sublist = [1,2,3,4]
li = [sublist] 
print(li) # => [[1, 2, 3, 4]]
for x in li:
    print(x) # => [1, 2, 3, 4]
    x.append(2) # 将2附加到x(即 [1, 2, 3, 4] <= 2),这包含在li中
print(x) # => [1, 2, 3, 4, 2]
print(li) # => [[1, 2, 3, 4, 2]]
英文:

Here is a similar code to yours, I broken down to explain it better:

sublist = [1,2,3,4]

sublist is a simple 1d array.

li = [sublist] 

li is a list containing sublist, effectivly a 2d array.

for x in li:

If you iterate over li, x is each element of li, so first a final iteration, x will be the list [1,2,3,4].

x.append(2)

Then you append 2 to x so you are effectivly appending to sublist.

The complete code looks like this:

sublist = [1,2,3,4]
li = [sublist] 
print(li) # =&gt; [[1, 2, 3, 4]]
for x in li:
    print(x) # =&gt; [1, 2, 3, 4]
    x.append(2) # appending 2 to x (i.e [1, 2, 3, 4] &lt;= 2) that is contained in li
print(x) # =&gt; [1, 2, 3, 4, 2]
print(li) # =&gt; [[1, 2, 3, 4, 2]]

huangapple
  • 本文由 发表于 2023年2月23日 19:44:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544377.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定