gpt4 book ai didi

Python内存分配

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

我对 Python 内存分配的工作原理非常感兴趣。

我写了两段代码:

1.

list = []
a = [1,2,3]
list.append(a)
a = [3,2,1]
print(list)
print(a)

2.

def change(list):
list[1] = 50
list[2] = 70

list = []
a = [1,2,3]
list.append(a)
change(a)
print(list)
print(a)

当我编译第一个代码时,我得到结果 [[1,2,3]] 和 [3,2,1]。

但是,当我编译第二个代码时,我得到的结果是 [1,50,70]。

在第一种情况下,我创建了一个对象“a”和一个数组“list”。当我将对象“a”附加到数组时,数组实际上指向它。然后,当我分配“a”新数组 [3,2,1] 时,对象 [1,2,3] 保存在数组中,“a”指向新数组 [3,2,1]。

在第二种情况下,我还创建了一个对象“a”和一个数组“list”。我将“a”附加到数组,还有一个指针指向“a”。然后我在数组“a”上调用一个方法。在调用函数并更改元素的值后,数组“list”仍然指向对象“a”,而没有创建新实例。

有人可以向我解释一下它的真正工作方式吗?

最佳答案

您在 Python 中创建的每个变量都是对对象的引用。列表是包含对不同对象的多个引用的对象。

python 中的几乎所有操作都修改这些引用,而不是对象。因此,当您执行 list[1] = 50 时,您正在修改列表项包含的第二个引用。

我发现一个有用的可视化工具是 Python Tutor

所以对于你的第一个例子

list = [] # you create a reference from `list` to the the new list object you have created
a = [1,2,3] # you create a reference from `a` to the new list you have created which itself contains 3 references to three objects, `1`, `2` and `3`.
list.append(a) # this adds another reference to `list` to the object referenced by `a` which is the object `[1, 2, 3]`
a = [3,2,1] # create a reference from `a` to the new list you have created which itself contains 3 references to three objects, `3`, `2` and `1`.
print(list) # print the object referenced by `list`
print(a) # print the object referenced by `a`

第二个例子

def change(list): # create a reference from `change` to a function object
list[1] = 50 #change the second reference in the object referenced by `list` to `50`
list[2] = 70 #change the third reference in the object referenced by `list` to `70`

list = [] # create a reference from `list` to a new list object
a = [1,2,3] # create a reference from `a` to a new list object which itself contains three references to three objects, `1`, `2` and `3`.
list.append(a) # add a reference to list to the object pointed to by `a`
change(a) # call the function referenced by change
print(list) # print the object referenced by `list`
print(a) # print the object referenced by `a`

关于Python内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53490783/

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