已有183人关注
关于字典放在for循环内和循环外的结果不一样
发表在Python图书答疑 2020-05-07 悬赏:5 学分 《Python从入门到项目实践》第10章 字典与集合
是否精华
版块置顶:

#第一个代码块:
print('*'*25+'外星人入侵'+'*'*25)
aliens = [ ]  #定义一个空列表
for  i  in range(0,8,1):  #生成8个外星人
    dictionary8 = {'color': 'green', 'points': 5, "speed": "10"}     #注意这里,字典放在for循环内
    aliens.append(dictionary8)
#现在,aliens列表里面有8个特征一样的外星人了
for alien in aliens[0:3]:      #只改变前三个外星人的特征
    if alien['color'] == 'green':
        alien['color'] = 'red'
        alien['points'] = '6'
        alien['speed'] = '20'
for aliens1 in aliens:  #输出aliens列表中的外星人
    print(aliens1)
#运行结果如下:
*************************外星人入侵*************************
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'green', 'points': 5, 'speed': '10'}
{'color': 'green', 'points': 5, 'speed': '10'}
{'color': 'green', 'points': 5, 'speed': '10'}
{'color': 'green', 'points': 5, 'speed': '10'}
{'color': 'green', 'points': 5, 'speed': '10'}
#运行正常无误
#现在,轻微修改一下第一个代码块,将字典放到空列表下面:
print('*'*25+'外星人入侵'+'*'*25)
aliens = [ ]
dictionary8 = {'color': 'green', 'points': 5, "speed": "10"}   #注意这里,字典放到了外面
for i in range(0,8,1):
    aliens.append(dictionary8)
for alien in aliens[0:3]:   #只修改前三个
    if alien['color'] == 'green':
        alien['color'] = 'red'
        alien['points'] = '6'
        alien['speed'] = '20'
for aliens1 in aliens:
    print(aliens1)
#运行结果如下:
*************************外星人入侵*************************
{'color': 'red', 'points': '6', 'speed': '20'}  #原本只改前三个外星人,但是所有的外星人都被改了
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'red', 'points': '6', 'speed': '20'}
{'color': 'red', 'points': '6', 'speed': '20'}


分享到:
手机同步功能介绍
友情提示:以下图书配套资源能够实现手机同步功能
明日微信公众号
明日之星 明日之星编程特训营
客服热线(每日9:00-17:00)
400 675 1066
mingrisoft@mingrisoft.com
吉林省明日科技有限公司Copyright ©2007-2022,mingrisoft.com, All Rights Reserved长春市北湖科技开发区盛北大街3333号长春北湖科技园项目一期A10号楼四、五层
吉ICP备10002740号-2吉公网安备22010202000132经营性网站备案信息 营业执照