如何在 Python 列表中打印多个最大值(整数)?

How to print multiple max values (integers) in Python list?

我有一个投票程序,我需要在其中找到投票的获胜者或找出得票最多的人之间是否有平局。我试图通过在列表中找到最大值(其中包含他们每个人获得了多少票),然后检查是否有任何其他值等于它来做到这一点。

使用的列表叫做votesEach,应该对应candGroup(所以votesEach中的第一个值就是候选人a的票数)。

这是我的问题: 如果 votesEach 等于 [1, 0, 0, 0],则显示正确的内容(即候选人 a 获胜)。然而, 如果有多个获胜者,则只显示其中一个(有时甚至是错误的)。比如votesEach是[0, 0, 1, 1],获胜者应该是c和d,但是a出现了两次。

可能是什么问题?

这是我的代码:

candGroup = ['a', 'b', 'c', 'd']
votesEach = [0, 0, 1, 1]
winnercounter = 0
for i in votesEach:
    if i == max(votesEach):
        winnercounter += 1
if winnercounter == 1:
    winner = candGroup[votesEach.index(max(votesEach))]
    print(winner, 'has won the vote with', max(votesEach), 'votes')
else:
    print(votesEach)
    for i in votesEach:
        if i == max(votesEach):
            print(candGroup[votesEach[i]], 'has won the vote with', max(votesEach), 'votes')

试试这个简单的方法,

candGroup = ['a', 'b', 'c', 'd']
votesEach = [0, 0, 1, 1]
# Zip function will zip two iterators and gives res in tuple like ('a',0),('b',0)..
# So by using those data we can filter out the winners by using maximum votes by creating a dictionary in a smart way
winners = {cand:votes for cand,votes in zip(candGroup,votesEach) if votes==max(votesEach)}
# Then here by iterating over each winners and getting the candidate name and votes
for candidate, votes in winners.items():
    print(candidate, 'has won the vote with', votes, 'votes')

输出:

c has won the vote with 1 votes
d has won the vote with 1 votes

首先求得最多票数:

maximum_vote = max(votesEach)
max_positions = [i for i, j in enumerate(votesEach) if j == maximum_vote]

然后找到获胜者:

winners = [candGroup[i] for i in max_positions]

winners 将是一个包含获奖者姓名的列表。

candGroup = ['a', 'b', 'c', 'd']
votesEach = [0, 0, 1, 1]

winningScore = max(votesEach)
winnersIndex = [index for index, value in enumerate(votesEach) if value == winningScore]

for i in winnersIndex:
    print(candGroup[i], "has won the vote with", winningScore, "votes" )