首页 > 解决方案 > 数组中的多个值都是最高的。我如何识别它们?

问题描述

所以基本上,我正在编写应该用于各种选举的代码。投票完成后,它会查看数组并确定最高票数(使用 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")

提前致谢

标签: pythonarrays

解决方案


您可以使用 collections.Counter和的组合max来计算列表中出现的最高/最大元素的出现次数。

from collections import Counter
counter = Counter(Votes).get(max(Votes))

推荐阅读