Python 的for循环,一个放在循环内,一个放在循环外,本想改变列表第一个元素(字典)的键值,为什么所有列表元素的的键值都改变了,为什么区别这么大?
1.
aliens=[]
for alien_number in range(5):
new_alien = {'color': 'green',
'point': 5,
}
aliens.append(new_alien)
print(aliens)
aliens[0]['color']=‘red’
print(aliens)
运行结果:
[{'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}]
[{'color': 'red', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}]
2.
aliens=[]
new_alien = {'color': 'green',
'point': 5,
}
for alien_number in range(5):
aliens.append(new_alien)
print(aliens)
aliens[0]['color']='red'
print(aliens)
运行结果:
[{'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}, {'color': 'green', 'point': 5}]
[{'color': 'red', 'point': 5}, {'color': 'red', 'point': 5}, {'color': 'red', 'point': 5}, {'color': 'red', 'point': 5}, {'color': 'red', 'point': 5}]