问题来了(来自Grok Learning):
You're running a poll to find out your friends' favourite dessert and decide to write a program to help you keep track of all the suggestions and who voted for each.
Your program should keep reading in lines (until an empty line) which contain the person's name, then a colon (:) then their favourite dessert.
Your program should work like this, printing out the results in any order:
他们想要:
Name:vote Harry:treacle tart
Name:vote Hermione:chocolate frogs
Name:vote Hagrid:rock cake
Name:vote Ron:chocolate frogs
Name:vote
treacle tart 1 vote(s): Harry
rock cake 1 vote(s): Hagrid
chocolate frogs 2 vote(s): Hermione Ron
这是我现在的代码:
votes= {}
line = input('Name:vote ')
while line:
name, vote = line.split(':')
if vote not in votes:
votes[vote] = [name]
else:
votes[vote].append(name)
line = input('Name:vote ')
for vote in votes:
print(vote, 'vote(s):', ' '.join(votes[vote]))
它给出:
Name:vote Harry:treacle tart
Name:vote Hermione:chocolate frogs
Name:vote Hagrid:rock cake
Name:vote Ron:chocolate frogs
Name:vote
treacle tart vote(s): Harry
rock cake vote(s): Hagrid
chocolate frogs vote(s): Hermione Ron
我不知道如何打印每个名字的频率
只需在输出中添加长度
votes[vote]
:print('{} {} vote(s): {}'.format(vote, len(votes[vote]), votes[vote]))
相关问题 更多 >
编程相关推荐