程序一中的第二行,把变量list3赋值给temp变量,而程序二中将list3[ : ]赋给变量temp,程序的计算结果却不相同,在第一行将列表赋给变量list3后,再赋给变量temp不可以吗,咋会导致结果错误
这是程序一,程序一与程序二对比,第二行不同。
>>> list3 = [1,2,3,4,5,1,2,3]
>>> temp = list3
>>> temp
[1, 2, 3, 4, 5, 1, 2, 3]
>>> list3.clear()
>>> list3
[]
>>> for each in temp:
if each not in list3:
list3.append(each)
>>> list3
[]
这是程序二,程序一与程序二对比,第二行不同。
>>> list3 = [1,2,3,4,5,1,2,3]
>>> temp = list3[ : ]
>>> temp
[1, 2, 3, 4, 5, 1, 2, 3]
>>> list3.clear()
>>> list3
[]
>>> for each in temp:
if each not in list3:
list3.append(each)
>>> list3
[]
temp = list3
这个是一个引用,temp实际上没有值,只是对list3 的一个引用,改变list3的董事temp也会改变。
temp = list3[:]
这个是把list3 的值完完全全复制一份给temp,list3再变化对temp也没影响。