gpt4 book ai didi

python - 列表操作(可变或不可变)?

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

我有这段代码:

list1 = [1, 2, 3]
list2 = list1
list1 = [4, 5, 6]

print(list2)
print(list1)

结果如下:

[1, 2, 3]
[4, 5, 6]

为什么 list2 还没有指向 [4, 5, 6]?我的印象是,由于列表是可变的,因此更改会同时影响 list1list2,因为在 RAM 中,两个列表都指向相同的项目序列。

如有任何解释,我们将不胜感激。

最佳答案

我在代码中添加了原因作为注释:

# list1 variable points to the memory location containing [1, 2, 3]
list1 = [1, 2, 3]
# list2 variable made to point to the memory location pointed to by list1
list2 = list1
# list1 variable made to point to the memory location containing
# a new list [4, 5, 6], list2 still pointing to [1, 2, 3]
list1 = [4, 5, 6]

print(list2) # list2 prints [1, 2, 3]
print(list1) # list1 prints [4, 5, 6]

关于python - 列表操作(可变或不可变)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29194991/

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