首页 > 解决方案 > 我得到一个索引错误,我不知道为什么

问题描述

所以我一直在为我正在做的一门课程编写脚本,但我遇到了一个错误

该程序的基本思想是一个投票系统,但是当计算出谁获得最多选票时,程序遇到了一个错误,错误读取

    if votes[0] > votes[1] and votes[0] > votes[2] and votes[0] > votes[3]:
IndexError: list index out of range

完整的功能在这里:

def getwinner():
    if votes[0] > votes[1] and votes[0] > votes[2] and votes[0] > votes[3]:
        print("Congratulations candidate",cands[0],"You win")
        if votes[1] > votes[0] and votes[1] > votes[2] and votes[1] > votes[3]:
            print("Congratulations candidate", cands[1], "You win")
            if votes[2] > votes[0] and votes[2] > votes[1] and votes[2] > votes[3]:
                print("Congratulations candidate", cands[2], "You win")
                if votes[3] > votes[0] and votes[3] > votes[1] and votes[3] > votes[2]:
                    print("Congratulations candidate", cands[3], "You win")

                    if votes[0] == votes[1] and votes[0] == votes[2] and votes[0] == votes[3]:
                        print("We have a tie")
                        if votes[1] == votes[0] and votes[1] == votes[2] and votes[1] == votes[3]:
                            print("We have a tie")
                            if votes[2] == votes[0] and votes[2] == votes[1] and votes[2] == votes[3]:
                                print("We have a tie")
                                if votes[3] == votes[0] and votes[3] == votes[1] and votes[3] == votes[2]:
                                    print("We have a tie")

选票保存到名为“votes”的数组中,候选人姓名保存到“cands”中。候选人姓名与“votes”数组中的选票对齐。但是有人可以解释这个问题吗?还有一种更简单、不那么冗长的方法吗?谢谢

标签: pythonindex-error

解决方案


您可以大大简化您的逻辑并轻松将其扩展到 4 个以上的玩家:

max_vote = max(votes)
if votes.count(max_vote) > 1:
    print("We have a tie")
else:
    winner_index = votes.index(max_vote)
    print("Congratulations candidate", cands[winner_index], "You win")

推荐阅读