不明白为什么循环不停止

2024-04-18 10:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中使用while循环来执行一个操作。然而,循环并没有在我期望的时候结束(当团队变空时)。代码如下:

while teams:
    if scores[0]<scores[1]:
        losers.append(teams[0])
        teams.remove(teams[0])
        teams.remove(teams[0])
        scores.remove(scores[0])
        scores.remove(scores[0])
    if scores[0]>scores[1]:
        losers.append(teams[1])
        teams.remove(teams[0])
        teams.remove(teams[0])
        scores.remove(scores[0])
        scores.remove(scores[0])
return losers

在测试代码时,我放入print语句,发现losers数组得到了预期的结果,但是循环在我期望它停止之后继续,当我已经在循环的最后一次迭代中删除了分数[0]时,检查分数[0]。为什么我的循环没有结束?你知道吗


Tags: 代码returnif数组语句团队分数remove
3条回答

解决方法是将第二个if语句更改为elif

while teams:
    if scores[0]<scores[1]:
        losers.append(teams[0])
        teams.remove(teams[0])
        teams.remove(teams[0])
        scores.remove(scores[0])
        scores.remove(scores[0])
    elif scores[0]>scores[1]:
        losers.append(teams[1])
        teams.remove(teams[0])
        teams.remove(teams[0])
        scores.remove(scores[0])
        scores.remove(scores[0])
return losers

问题是,当teamsscores列表到达最后一对,并且第一个if语句中的条件是True时,最后一对被删除,两个列表都变为空。你知道吗

然后计算第二个if条件,但是scores列表现在是空的(由于前面的if匹配),因此引发了一个IndexError。你知道吗

将其更改为elif意味着仅当第一个条件为False时,才会计算第二个条件。现在,循环在每次迭代中只处理一对团队/分数,对空的team的测试将成功。你知道吗

您可以使用以下命令使while循环更加清晰:

while teams:
    if scores[0] < scores[1]:
        losers.append(teams[0])
    elif scores[0] > scores[1]:
        losers.append(teams[1])
    else:
        # this should never happen
        print('Error: drawn match detected!')
        losers.append(None)    # or simply ignore if that makes sense

    teams[:] = teams[2:]    # remove the first 2 items
    scores[:] = scores[2:]

如果循环没有结束是因为teams永远不会变空。你的假设“循环不会在[…]teams变空时结束”是不正确的,并且可能误导了你解决问题的尝试。你知道吗

仔细检查回路的状况。如果条件永远不等于false,循环将变为无穷大。你知道吗

请参阅http://www.tutorialspoint.com/python/python_while_loop.htm的“无限循环”部分。你知道吗

相关问题 更多 >