添加到字典并从中打印

2024-04-26 09:28:00 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我现在需要一些帮助来创建投票系统

Name:vote Greg:chocolate
Name:vote Teena:macaroons
Name:vote Georgina:apple pie
Name:vote Will:chocolate
Name:vote Sophia:gelato
Name:vote Sam:ice cream
Name:vote James:chocolate
Name:vote Kirsten:gelato
Name:vote 
apple pie 1 vote(s): Georgina
gelato 2 vote(s): Sophia Kirsten
chocolate 3 vote(s): Greg Will James
macaroons 1 vote(s): Teena
ice cream 1 vote(s): Sam

我现在的代码完全被破坏了,因为我对字典没那么在行。有什么提示吗。你知道吗

Current Code:
votes = {}

userinput = input("Name:vote ")
for word in userinput.strip().split():
  name = ""
  food = ""
  key = (name, food)
  votes[key]
print(votes)

提前谢谢


Tags: nameapplesamwillvotepiegelatoice
1条回答
网友
1楼 · 发布于 2024-04-26 09:28:00

假设你希望你的输入是严格的'用户:输入如果你想无限期地重复这个过程,你需要一个循环,这取决于你需要输入多少选票。每次用户添加条目时,您都会将其添加到列表中。您可以基于输入设置子句变量,例如,如果用户键入“end”,则会中断循环。你知道吗

userinputs = []
end = False

while end == False:
    entry = input("Enter Name:Vote")
    if entry == 'end':
        end = True
    else:
        userinputs.append(entry)

一旦你有了它,你就可以用另一个循环来填充字典,就像你做的那样。因为输入约定是严格的姓名:投票'可以使用':'字符拆分,并将相应的值添加到字典中:

for entry in userinputs:
  name = entry.split(':')[0]
  food = entry.split(':')[1]
  votes[name] = food

print(votes)

我的建议是,考虑一下您可以如何设计这样一种方式,即输入约定不是严格意义上的姓名:投票,以及如何使这个程序对错误(其中有许多错误)更加健壮。你知道吗

相关问题 更多 >