Python 如何在多数选举程序中打印多个获胜者?

Python 如何在多数选举程序中打印多个获胜者?,python,Python,我正在尝试创建一个模拟多数选举的程序。当有1个赢家时,代码运行良好,但当有平局和多个赢家时,代码会被卡住。我尝试使用if-elif循环,但它没有按预期工作。如果您可以修改代码使其正常工作,这将非常有用 candidate_number = int(input("Number of candidates: ")) while candidate_number <= 0: candidate_number = int(input("Number o

我正在尝试创建一个模拟多数选举的程序。当有1个赢家时,代码运行良好,但当有平局和多个赢家时,代码会被卡住。我尝试使用if-elif循环,但它没有按预期工作。如果您可以修改代码使其正常工作,这将非常有用

candidate_number = int(input("Number of candidates: "))
while candidate_number <= 0:
        candidate_number = int(input("Number of candidates: "))

candidates = []
votes = []
find = []
tie = []


for i in range(1, 1 + candidate_number):
  a = input("Candidate: ").upper()
  while a in candidates:
      a = input("Candidate: ").upper()
  else:
      candidates.append(a)

print("")
voter_number = int(input("Number of voters: "))
while voter_number <= 0:
    voter_number = int(input("Number of voters: "))


for i in range(1, 1 + voter_number):
    a = input("Vote: ").upper()
    votes.append(a)

for i in range(len(votes)):
   find.append(votes.count(votes[i]))

k = find.index(max(find))
for i in range(3):
    print("")
print("Winner: " + votes[k])
candidate\u number=int(输入(“候选数量:”)

当候选数量时,如果只有一个最大值,则可以

if find.count(max(find)) == 1:
然后使用旧方法(针对单个冬季)或
针对
-循环显示所有获奖者

max_count = max(find)

for c in candidates:
    if votes.count(c) == max_count:
        print('MAX VOTES:', c)

最小工作代码

votes = ['A', 'B', 'A', 'Mr. X', 'B', 'C', 'D', 'C']
candidates = sorted(set(votes))  # create list of candidates base on votes
find = []

# display all candidates
print('--- candidates ---')
for c in candidates:
    print(c)

# count votes and also display it 
print('--- count votes ---')
for c in candidates:
    count = votes.count(c)
    find.append(count)
    print(c, ':', count)
  
# find max count  
print('--- max ---')

max_count = max(find)
print('max_count:', max_count)

print('\n\n--- results ---\n\n')

# check if only one max count
if find.count(max_count) == 1:
    # display winner
    index = find.index(max(find))
    print('Winner:', votes[index])
else:
    # display all 
    for c in candidates:
        if votes.count(c) == max_count:
            print('Draw:', c)

编辑:x2

if find.count(max_count) == 1:

    # ... code ...

else:
    # display all 

    # --- before loop ---

    all_winners = []

    # --- loop ---

    for c in candidates:
        if votes.count(c) == max_count:
            all_winners.append(c)

    # --- after loop ---        

    print('Draw:', ",".join(all_winners) )

您可能需要
for
-循环检查所有项目并显示具有最大值的项目,而不是
查找.index()
,或者您可能需要使用
索引()
和另一个值
索引(值,开始)
,该值将搜索最后找到的值-即
索引(max(find),k+1)
-您必须在循环中运行它,直到
find()
引发错误。此代码中的大部分内容完全无关。对于失败的情况,只需直接在代码段中键入输入。请记住在问题中给出输入和预期输出。它可以工作,但我可以使它在
中为
-loop
append()
添加到某个列表中,然后使用
,“,”转换为
A,B
。加入(列表)
查看答案中的新代码。很抱歉再次打扰您。我尝试了你的代码,但出现了一个bug。即使只有1名获胜者,代码也会打印“抽签”而不是“获胜者”。你看到我的代码了吗?如果find.count(max\u count)=1:
它必须位于
else
的内部,如果使用它,则检查
print(find.count(max\u count))
,因为有更多的元素具有此值。