2016-11-16 16 views
0

有人會告訴我這兩個街區之間的區別嗎?我很難弄清楚爲什麼第二個只在本地更改嵌套列表,而第一個更改全局。在我看來,他們做同樣的事情。爲什麼new_list必須放在for循環中以防止全局變化?

my_list = [ ] 
new_list = [0, 0, 0 ]## outside the loop 
for index in range(5): 
    my_list.append(new_list) 
my_list[0][1] = 5 
print(my_list) 

## result 
[[0, 5, 0], [0, 5, 0], [0, 5, 0], [0, 5, 0], [0, 5, 0]] 


my_list = [ ] 
for index in range(5): 
    new_list = [0, 0, 0 ] ## inside the loop 
    my_list.append(new_list) 
my_list[0][1] = 5 
print(my_list) 
## result 
[[0, 5, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] 

回答

1

因爲for循環內,new_list獲取的重新定義,有效指的每次迭代不同的列表對象。

打印id S爲第二種情況揭示了這一點:

print(*map(id, my_list)) # Notice the different ids 
140609203176456 140609194670088 140609194608840 140609212158216 140609194670152 

循環外,您將追加相同的列表對象,相同的參考。通過所有參考可以看到更改。

打印id S表示這種情況下示出了相同id(即,相同的列表)的存在:

print(*map(id, my_list)) # same id. 
140609194670088 140609194670088 140609194670088 140609194670088 140609194670088 
相關問題