学习python入门到实践这本书第六章
aliens = []
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} #new_alien在嵌套前定义
for alien_number in range (0,30):
aliens.append(new_alien)
for alien in aliens[0:8]: #选择列表aliens0-7的字典
if alien['color'] == 'green': #修改键值
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[0:12]: #选择列表aliens0-11字典
print(alien)
运行如下
{'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'}
{'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'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
Press any key to continue . . .#并没有达到选择性修改列表字典键值,并且输出aliens全部字典时发现键值全部被修改
aliens = []
for alien_number in range (0,30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'} #new_alien在嵌套内定义
aliens.append(new_alien)
for alien in aliens[0:8]: #选择列表aliens0-7的字典
if alien['color'] == 'green': #修改键值
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[0:12]: #选择列表aliens0-11字典
print(alien)
运行如下{'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'}
{'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'}
Press any key to continue . . .#到达目的,aliens列表选择性字典键值被修改
于是有了疑惑,为什么new_alien在嵌套时位于for循环内外会有这么大差距