计划对一个政党的投票数,然后按字母顺序排列

时间:2014-04-21 15:03:12

标签: python-3.x

我目前正在处理的程序存在一个小问题。在这个程序中,我提示用户输入他们想要投票的政党/政党的名称。在此之后,我计算每一方的投票数,然后根据政党的名称按字母顺序安排投票给党/党。这是我的计划:

print("Independent Electoral Commission\n--------------------------------")

votes = []

#User is prompted to enter the political party/parties they want to vote for
vote = input("Enter the names of parties (terminated by DONE):\n")
while vote != 'DONE':
    votes.append(vote) # This appends/adds the vote(s) the user types in, to votes
    vote = input("")

counters={}

# This calculates the total number of votes towards a certain political party
for vote in votes:
    if not vote in counters:
        counters[vote]=0
    counters[vote] += 1

print("\n""Vote counts:")
for vote in counters:
    print(vote + ' '*(10 - len(vote)) ,'-',counters[vote])

我正在寻找的输出是:

Independent Electoral Commission
--------------------------------
Enter the names of parties (terminated by DONE):
DAL
ACNO
OPT
DAL
DAL
PRQ
DAL
DONE

Vote counts:
ACNO       - 1
DAL        - 4
OPT        - 1
PRQ        - 1

相反,我得到了这个:

Independent Electoral Commission
--------------------------------
Enter the names of parties (terminated by DONE):
DAL
ACNO
OPT
DAL
DAL
PRQ
DAL
DONE

Vote counts:
PRQ        - 1
DAL        - 4
ACNO       - 1
OPT        - 1

1 个答案:

答案 0 :(得分:0)

在计算一方的总票数后,只需对键进行排序:

sorted_parties = sorted(counters.keys())

然后,将其打印为:

print("\n""Vote counts:")
for vote in sorted_parties:
    print(vote + ' '*(10 - len(vote)) ,'-',counters[vote])