0

我正在努力使用“排序”功能打印政党名称和投票结果以实现字母顺序。查看下图,您可以找到输入示例以及输出应如何显示: 预期输入和输出示例

parties = {}

print("Independent Electoral Commission")
print("--------------------------------")
string1 = input("Enter the names of parties (terminated by DONE):\n")

while True:
    string1 = input()
    if string1 == 'DONE':
        break
    if string1 not in parties:
        parties[string1] = 1
    else:
        parties[string1] = parties[string1] + 1
print("")
print("Vote counts:")
for key in parties:
    value = (parties[key])
    
    print("{: <10}".format(key),"-", value)        

对于相同的输入,我的程序产生: 我的输出

4

2 回答 2

2

使用sorted功能

parties = {}

print("Independent Electoral Commission")
print("--------------------------------")
print("Enter the names of parties (terminated by DONE):\n") # Print Instead INPUT otherwise FIRST input will be skipped

while True:
    string1 = input()
    if string1=="DONE":
        break
    if string1 not in parties:
        parties[string1] = 1
        
    else:
        parties[string1] += 1
        

print("")
print("Vote counts:")
for key in sorted(parties):
    value = (parties[key])
    
    print("{: <10}".format(key),"-", value) e) 

于 2021-05-27T13:32:37.160 回答
1

我不知道你为什么使用输入函数来打印一行(它接受一个输入,但它不计入while循环通过再次输入来覆盖变量'string1')。相反,你应该这样做:

print("Enter the names of parties (terminated by DONE):\n")

是的,您可以使用Giorgi Imerlishvillisorted()的回答中提到的 方法对字典键进行排序

于 2021-05-27T13:53:19.193 回答