繁体   English   中英

我得到一个索引错误,我不知道为什么

[英]Im getting an index error and im not sure why

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

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

    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”数组中的选票对齐。 但是有人可以解释这个问题吗?还有一种更简单、不那么冗长的方法吗? 谢谢

您可以大大简化您的逻辑并轻松将其扩展到 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 没有任何内容,并且没有其他原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM