我收到索引错误,但不确定为什么

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

该程序的基本思想是投票系统,但是在计算出得票最多的人时,该程序会遇到错误,错误显示为

    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”数组中的投票对齐。但是有人可以解释这个问题吗,还有没有更简单,更短的解决方法呢?谢谢

shuojie 回答:我收到索引错误,但不确定为什么

您可以大大简化逻辑,轻松地将其扩展到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")
,

似乎您的列表votes没有4个值。它会抱怨说,如果索引3没有任何内容,那么索引3就没有任何内容,并且没有其他原因。

本文链接:https://www.f2er.com/3073597.html

大家都在问