因此,例如,您有:
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句