python中列表的可变性 [英] Mutability of lists in python

查看:136
本文介绍了python中列表的可变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例一:更改附加到b的值将更改原始列表l中的值

Example one: Changing the value that has been appended to b changes the value in the original list l

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

示例2:将l1附加到ans,然后修改l1的值.但是,ans中的值保持不变.

Example 2: l1 is appended to ans and then the value of l1 is modified. However, the value in ans remains the same.

>>> l1 = [1, 2, 3]
>>> ans = []
>>> ans.append(l1)
>>> ans
[[1, 2, 3]]
>>> l1 = [2, 3, 4]
>>> ans
[[1, 2, 3]]

我似乎缺少有关列表可变性的一些基本知识.有人可以指出吗?

I seem to be missing some fundamental point about the mutability of lists. Could someone please point it out?

推荐答案

在您的第一个示例中,lb一样都是指针.

In your first example, l is a pointer, as well as b.

l附加到b,因此b[0]现在引用该指针.

l is then appended to b, so b[0] now refers to the pointer.

接下来,将4附加到b[0],这与l相同,因此在b[0] l上都添加了4.

Next, you append 4 to b[0], which is the same thing as l, so 4 is added to both b[0] and l.

在第二个示例中,ans包含l1的指针,就像b包含l的指针

In your second example, ans contains the pointer of l1, just like b contained the pointer of l

然后,通过将l1本身分配给另一个数组来更改它,因此l1进行了更改,但ans[0]却没有.

Then, you changed l1 itself by assigning it to a different array, so l1 changed but ans[0] did not.

最大的收获是append仅更改列表,并且指针保持不变.但是,当您将变量设置为其他列表时,指针会更改.

The biggest takeaway from this is that append just changes the list, and the pointer remains the same. But when you set a variable to a different list, the pointer changes.

这篇关于python中列表的可变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆