gpt4 book ai didi

python - Python3 list.copy() 为何是浅拷贝?

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

我对浅拷贝的理解是

a = [1,2,3]
b = a
a, b # ([1, 2, 3], [1, 2, 3])
a[0] = 99
a, b # ([99, 2, 3], [99, 2, 3])

但是,Python 3 文档说 list.copy() 返回列表的浅拷贝。相当于 a[:]. 但这对我来说似乎是一个深拷贝。为什么文档称其为浅拷贝?

a = [1,2,3]
b = a.copy()
a, b # ([1, 2, 3], [1, 2, 3])
a[0] = 99
a, b # ([99, 2, 3], [1, 2, 3])

最佳答案

a = [1,2,3,4]
b = [5,6,7,8]
c = [a,b,25]
d = c.copy() # shallow, contains [a-ref,b-ref, ref of 25]

print(a)
print(b)
print(c)
print(d)
print("")

d[2] = 99 # modify only d's 3rd element

print(a)
print(b)
print(c)
print(d)
print("")

d[1].append(15) # change b's refs content

print(a)
print(b)
print(c)
print(d)
print("")

输出:

[1, 2, 3, 4]
[5, 6, 7, 8]
[[1, 2, 3, 4], [5, 6, 7, 8], 25]
[[1, 2, 3, 4], [5, 6, 7, 8], 25]

[1, 2, 3, 4]
[5, 6, 7, 8]
[[1, 2, 3, 4], [5, 6, 7, 8], 25]
[[1, 2, 3, 4], [5, 6, 7, 8], 99] # changing d[2] - its a shallow copy with
# a int thats "unique" to this list

[1, 2, 3, 4]
[5, 6, 7, 8, 15]
[[1, 2, 3, 4], [5, 6, 7, 8, 15], 25] # appended to b's ref - its just a shallow copy so
[[1, 2, 3, 4], [5, 6, 7, 8, 15], 99] # changes are in both

关于python - Python3 list.copy() 为何是浅拷贝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969842/

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