当您有一个多级列表[python]时,该列表中的引用点是如何变化的?
例如,你有:当您有一个多级列表[python]时,该列表中的引用点是如何变化的?,python,list,slice,Python,List,Slice,例如,你有: a = [1,2] b = [a,3] c = b[:] a[0] = 7 b[1] = 8 print c 你得到了[[7,2,3] 为什么3没有改为8?正如其他人提到的,基本原则是,当你分配c时,你是在做一个“浅拷贝” 要详细说明,您有以下几点: a = [1,2] # a = list(1,2) at address AAA b = [a, 3] # b = list( [REFERENCE to AAA], 3) at address BBB c = b[:
a = [1,2]
b = [a,3]
c = b[:]
a[0] = 7
b[1] = 8
print c
你得到了[[7,2,3]
为什么
3
没有改为8
?正如其他人提到的,基本原则是,当你分配c
时,你是在做一个“浅拷贝”
要详细说明,您有以下几点:
a = [1,2]
# a = list(1,2) at address AAA
b = [a, 3]
# b = list( [REFERENCE to AAA], 3) at address BBB
c = b[:]
# c = NEW list( b[0], b[1] ) at address CCC
# c = list( [REFERENCE to AAA], 3) at address CCC
a[0] = 7
# change item at AAA, offset [0], to 7
# 'b' points to AAA, so it will see change
# 'c' points to AAA, so it will see change
b[1] = 8
# change item at BBB, offset [1], to 8
# 'a' doesn't know about this, so it doesn't care.
# 'c' doesn't point to BBB, so it doesn't see the change.
print c
# Prints CCC offset [0], which refers to the AAA list, as changed,
# then prints CCC offset [1], which is still 3.