Python3 list.copy()是如何浅拷贝的?

时间:2017-12-25 15:14:04

标签: python python-3.x

我对浅拷贝的理解是

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 = [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])

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

你对第一个的理解是错误的。 b不是a的副本,它是同一事物的另一个名称(这是别名)。 a.copy()是浅拷贝,因为它只复制第一级。使用a = [ [1,2], 3]再次尝试测试。