python - 我得到一个索引错误,我不知道为什么
问题描述
所以我一直在为我正在做的一门课程编写脚本,但我遇到了一个错误
该程序的基本思想是一个投票系统,但是当计算出谁获得最多选票时,程序遇到了一个错误,错误读取
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")
推荐阅读
- google-sheets - 如何通过 API 在 Google 表格中启用“数据标签”?
- aop - Spring AOP - 在带注释的方法之间传递参数
- r - 从 R 中的列表创建数据框
- python - 我应该如何使用 GEKKO 对 log 或 sqrt 建模?约束
- tensorflow - tf.keras 中的 val_sample_weights 是否损坏?
- postgresql - 超过 3 个表的索引 id 连接出乎意料地慢
- .net-core - 为什么在 F# 任务中引用此 IDisposable 时会被释放?
- c# - 使用运算符进行树评估
- django - Django rest框架:省略字段为空的dict
- java - 第一次运行 netbeans 11.1 时,我不断收到此错误。有谁知道它的解决方案?