爲什麼代碼中的這個小改動會使此代碼的工作方式不同。我只是在學習Python。誰能以簡單的方式解釋? 編輯: 我沒有意識到追加到列表字典是指向相同的字典,而不是它的實際副本。我在這篇文章之前試圖找到解決方案,但可能表達我的問題有點不同,這可能會導致有經驗的程序員將其視爲重複。嵌套字典已更改我不明白爲什麼
輸入
# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# Show the first 5 aliens:
for alien in aliens[:5]:
print(alien)
print("...")
# Show how many aliens have been created.
print("Total number of aliens: " + str(len(aliens)))
輸出
{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 10, 'color': 'yellow', 'speed': 'medium'}
{'points': 5, 'color': 'green', 'speed': 'slow'}
{'points': 5, 'color': 'green', 'speed': 'slow'}
...
Total number of aliens: 30
現在改變了代碼,我會初始化字典中的第一個外for循環
輸入
# Make an empty list for storing aliens.
aliens = []
# HERE IS THE CHANGE
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
# Make 30 green aliens.
for alien_number in range(30):
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
# Show the first 5 aliens:
for alien in aliens[:5]:
print(alien)
print("...")
# Show how many aliens have been created.
print("Total number of aliens: " + str(len(aliens)))
輸出
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
...
Total number of aliens: 30
爲什麼在第二個是整個字典改變,而不只是前3個詞典?
之前,您每次都通過循環創建一個新字典。現在,您只能創建一個字典,並將其添加到同一個列表中30次。使用列表中的哪個索引並不重要,它仍指向相同的字典。 –
@BrendanAbel是正確的 - 與其他語言不同,Python中的'='*從不*做任何東西的副本。 '{'color':'green','points':5,'speed':'slow'}'表達式會創建一個新的'dict',並且在您的原始代碼中運行這個30次,但在第二次只運行一次。 –
Ahh geez現在我明白了@Brendan ......謝謝...閱讀您的評論3 *更多。我今天有點慢。非常感謝你解釋它;) – martin