python - 数组中的多个值都是最高的。我如何识别它们?
问题描述
所以基本上,我正在编写应该用于各种选举的代码。投票完成后,它会查看数组并确定最高票数(使用 python 中的 max() 函数)并显示获胜者。但是如果有多个获胜者(平局) max() 无法确定获胜者。有谁知道这个的解决方案?
下面我附上了一个简化版
NumberofStudents = int(input("Enter the number of students: "))
while NumberofStudents <=28 or NumberofStudents >=35:
print("Number of Students must be in range 28 to 35")
NumberofStudents = int(input("Enter the number of students: "))
NumberofCandidates = int(input("Enter the number of candidates: "))
while NumberofCandidates <=1 or NumberofCandidates >=4 :
print("Number of Candidates must be in range 1 to 4")
NumberofCandidates = int(input("Enter the number of candidates: "))
NamesofCandidates=[""]*NumberofCandidates
Votes=[0]*NumberofCandidates
SkipVote=0
VoterIDList=[]
FraudVote=0
for x in range(0,NumberofCandidates):
NamesofCandidates[x] = input("Enter the name of candidates: ")
for v in range(0,NumberofStudents):
print("You are voting for a student representative")
print("You are the student number",v+1,"of",NumberofStudents,"to vote")
print("")
print("Below is the list of options")
print("")
for i in range(0,NumberofCandidates):
print(i,NamesofCandidates[i])
print("")
print("Enter the number seen next to the candidate that you would like to vote for below")
VoteID = int(input())
while VoteID < -1 or VoteID > NumberofCandidates:
print("Sorry but there is no option labeled",VoteID,"Try again")
VoteID = int(input())
a=Votes[VoteID]
b=a+1
Votes[VoteID]=b
WinNumber=max(Votes)
WinID=Votes.index(WinNumber)
Winner=NamesofCandidates[WinID]
a=WinNumber*100
Percentage=a/NumberofStudents
print("Results for elections")
print("")
print("The winner is",Winner,"with",Percentage,"percent and",WinNumber,"votes")
提前致谢
解决方案
您可以使用 collections.Counter
和的组合max
来计算列表中出现的最高/最大元素的出现次数。
from collections import Counter
counter = Counter(Votes).get(max(Votes))
推荐阅读
- sql - 需要基于Condition的SQL查询
- angular - 无法使用角度 7 在表行中动态更改输入数据类型
- flutter - 如何访问 Flutter for desktop (macOS) 应用程序中的方法
- material-ui - Trouble using gatsby-image with material-ui CardMedia component
- oauth-2.0 - OData vs oAuth -- What is the difference?
- python - django-hosts - 如何管理子域 .django.urls.exceptions.Resolver404 中的无效 url?
- javascript - enabling ShadowDOM not working with aurelia 2
- python - 如何训练一个张量流模型来准确分类睁眼和闭眼?
- binding - RabbitMQ 交换绑定复制消息发布到一个交换跨两个其他交换
- java - 使用 VSCode (spring-boot-starter-email) 发送电子邮件