2014-04-21 6 views
0

현재 작업하고있는 프로그램에 약간의 문제가 있습니다. 이 프로그램에서 나는 사용자가 투표하고자하는 정당/정당의 이름을 입력하게합니다. 이 후 나는 각 당에 대한 투표 수를 세고 정당의 이름에 따라 당/정당에 대한 투표 수를 알파벳 순으로 정렬한다.정당에 투표 할 투표 수를 계산하고 알파벳 순서로 정렬하는 프로그램

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: 
PRQ  - 1 
DAL  - 4 
ACNO  - 1 
OPT  - 1 
+0

'dict'이 주문되지 않았습니다. 순서대로 인쇄하려면 키를 명시 적으로 정렬하십시오. – geoffspear

답변

0

그냥 키를 정렬 :

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 

대신 나는이 얻을 여기 내 프로그램입니다 파티에 투표 :

sorted_parties = sorted(counters.keys()) 

그러면 다음과 같이 인쇄하십시오.

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

대단히 감사합니다. – user3556825

관련 문제