发现用b=a[:] , 再给b赋值, 不会影响a; 直接给a[:]赋值却会影响a
a=5
b=a
print(a,b)
b=3
print(a,b)
a=6
print(a,b)
5 5
5 3
6 3
c=[1,2,3,4]
d=c
print(c,d)
c[0]=5
print(c,d)
d[0]=6
print(c,d)
[1, 2, 3, 4] [1, 2, 3, 4]
[5, 2, 3, 4] [5, 2, 3, 4]
[6, 2, 3, 4] [6, 2, 3, 4]
c=[1,2,3,4]
d=c[:]
print(c,d)
c[0]=5
print(c,d)
d[0]=6
print(c,d)
[1, 2, 3, 4] [1, 2, 3, 4]
[5, 2, 3, 4] [1, 2, 3, 4]
[5, 2, 3, 4] [6, 2, 3, 4]
c=[1,2,[1,2,3],3,4]
d=c[:]
print(c,d)
c[0]=5
c[2][0]=7
print(c,d)
d[0]=6
print(c,d)
[1, 2, [1, 2, 3], 3, 4] [1, 2, [1, 2, 3], 3, 4]
[5, 2, [7, 2, 3], 3, 4] [1, 2, [7, 2, 3], 3, 4]
[5, 2, [7, 2, 3], 3, 4] [6, 2, [7, 2, 3], 3, 4]
import copy
c=[1,2,3,4]
d=copy.deepcopy(c)
print(c,d)
c[0]=5
print(c,d)
d[0]=6
print(c,d)
[1, 2, 3, 4] [1, 2, 3, 4]
[5, 2, 3, 4] [1, 2, 3, 4]
[5, 2, 3, 4] [6, 2, 3, 4]
a = [0, [1, 2], 3]
b = a[:]
a[0] = 8
a[1][1] = 9
print(a,b)
[8, [1, 9], 3] [0, [1, 9], 3]
'''
学习中遇到问题没人解答?小编创建了一个Python学习交流QQ群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import copy
a = [0, [1, 2], 3]
b = copy.deepcopy(a)
a[0] = 8
a[1][1] = 9
print(a,b)
[8, [1, 9], 3] [0, [1, 2], 3]
|