gpt4 book ai didi

python - 在python中分配被视为对象的副本

转载 作者:太空宇宙 更新时间:2023-11-03 13:29:09 25 4
gpt4 key购买 nike

我不明白为什么在第一个例子中,b 被认为是 a 的副本,它会随着 a 而改变> 但不是在第二个例子中

def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
return alist

a=[3,2,1]
b=a
a=bubbleSort(a)
print(a)
print(b)

输出:

[1, 2, 3]
[1, 2, 3]

a=[3,2,1]
b=a
a=[1,2,3]

print(a)
print(b)

输出:

[1, 2, 3]
[3, 2, 1]

最佳答案

a=[3,2,1]
b=a # **here you're refrencing by memory not value**
a=bubbleSort(a)

print id(a)
print id(b)

# these both will give you same memory reference

print(a)
print(b)

在第二个示例中,当您执行 b=a 时,您是通过内存引用的,但是当您执行 a=[1,2,3] 时,您正在将 a 关联到一个新的内存引用 b 仍然绑定(bind)到旧的。

a = [3,2,1]
b=a

print id(b) #4376879184
print id(a) #4376879184


#they will be having the same id

a = [1,2,3]
#now you have assigned a new address which will have the new array

print id(b) #4376879184
print id(a) #4377341464
#they will be having different id now

关于python - 在python中分配被视为对象的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50134883/

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