自学python的新人 2022-06-29 14:48 采纳率: 88.9%
浏览 28
已结题

python双重for if这么循环的


aliens = []
# 创建30个绿色的外星人
for alien_number in range (0,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
        for alien in aliens[0:3]:
            if alien['color'] == 'green':
                alien['color'] = 'yellow'
                alien['speed'] = 'medium'
                alien['points'] = 10
            elif alien['color'] == 'yellow':
                alien['color'] = 'red'
                alien['speed'] = 'fast'
                alien['points'] = 15
for alien in aliens[0:5]:
    print(alien)
    print("...")

{'color': 'red', 'points': 15, 'speed': 'fast'}
......
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
......
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
......
{'color': 'green', 'points': 5, 'speed': 'slow'}
......
{'color': 'green', 'points': 5, 'speed': 'slow'}
......

进程已结束,退出代码0


  • 写回答

2条回答 默认 最新

  • 请叫我问哥 新星创作者: python技术领域 2022-06-29 17:17
    关注

    除了第一层的第一个元素外,后面都是先执行第二层的代码,再执行第一层。真正的循环顺序如下:
    第一层第1个元素--> 第二层第1个元素-->第二层第2个元素-->第二层第3个元素-->第一层第2个元素-->第一层第三个元素-->循环结束
    因为在第二层里已经把三个元素的颜色从green改成了yellow,所以第一层的后面两个元素 if 判断不成立,就不会再执行第二层循环了。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月7日
  • 已采纳回答 6月29日
  • 修改了问题 6月29日
  • 创建了问题 6月29日