python中列表的可变性 [英] Mutability of lists in 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?
推荐答案
在您的第一个示例中,l
和b
一样都是指针.
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屋!