切片操作后,编号5没有添加到列表中。不确定为什么吗?
尝试移除切片,然后获得所需的输出。
oldlist = [0,1,2,3]
newlist = oldlist
print (newlist)
oldlist.append(4)
print (newlist)
newlist = oldlist[:]
print (newlist)
oldlist.append(5)
print (newlist)
预期产量
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4,5]
我得到的输出是
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
答案 0 :(得分:1)
less-loader
与直接分配不同,这将创建列表的副本。在此之后,对newlist = oldlist[:]
的更改将不适用于oldlist
。