python 为什么没对aliens变量内字典修改赋值 反而影响了?

aliens = []

for aliens_number in range(30):
new_aluen = {'color':'green','points':5,'speed':'slow'}
aliens.append(new_aluen)

print (aliens[:1])

for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10

print (alien,end = '\n')
print (aliens,end = '\n')

-----------------------------
[{'color': 'green', 'points': 5, 'speed': 'slow'}]
{'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': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}, {'color': 'green', 'points': 5, 'speed': 'slow'}]

这一句会重新建立这个字典,它使用的地址会发生改变,也就是说,它与这前的new_alien是完全不同的。
因此,如果这一句在for外面的话,aliens中的每个元素实际上都是保存的同一个字典对象,对其中一个进行修改,都是修改aliens引用的那个字典,因此会看到aliens中每个字典都同步改变了。
如果在for中去为new_alien赋值,每次都会得到一个新的字典,aliens中的每个元素都是不同的,修改其中一个不会影响到其它字典。
温馨提示:答案为网友推荐,仅供参考