Python字典-同时输入两个或三个用户,并在单独的行中输出



我几乎完成了构建一个字典,计算输入的每个元素的数量…虽然,例如,如果我输入咖啡水,然后输入,打印1咖啡水在同一行…我想让它打印:

1 coffee
1 water

分行

我做错了什么?

dictionary = {}  
while True: 
user_input = input("Input: ")
dictionary[user_input] = dictionary.get(user_input, 0) + 1
for key, value in sorted(dictionary.items()):
print(value, key.upper())
print("n")

好吧,事情是这样的。

input()在按Enter键时结束。比如,如果你输入"咖啡水"然后按回车键,它会认为那是你要输入的物品的名称。(">"咖啡水)

基本上每次只输入一项。

或者,如果您愿意,可以用空格分隔,并支持同时添加多个项目。比如:

dictionary = {}
value = input("Enter item: ")
while value !="":   
value = value.split(" ") # split by space.
# if there's no space (i.e. only one item is entered this time, this gives a list with a single item in it. (the word entered)
for item in value:
if item in dictionary.keys(): # if the item exists, add 1 to its counter
dictionary[item] +=1
else: # if the item doesn't exist, set its counter to 1
dictionary[item] = 1
value = input("Enter item: ")

for key, value in sorted(dictionary.items()):
print(value, key.upper())

进入:

coffee
water
water coffee 

给:

2 COFFEE
2 WATER

注意:如果项目名称中有空格,则会中断此操作。比如"水瓶">

还可以阅读defaultdict模块

要解决您在上一条评论中提到的问题,并提供while循环的转义,我将修改您的代码如下。这改变了第2、5、6、8和9行。我很难把我的代码放进去。如果你有任何问题,请告诉我。

dictionary = {}  
i = 1
while True: 
user_input = input("Input: ")   
if user_input == "":
break #provides escape   
dictionary[user_input] =  dictionary.get(user_input, i) 
i = i + 1 #solves numbering problem
for key, value in (dictionary.items()):
print(f"{value} {key.upper()}", end=" ")   
print("n")

我的电脑不在我面前,所以这是一种伪代码。

试试这样写:

input_list = user_input.split()
for i in input_list:
dictionary[i] = dictionary.get(i, 0) + 1
print(i)

默认情况下,输入将是一个字符串,因此您不能直接对其进行操作,您需要拆分它。

编辑:检查Yarin_007的答案,但是你可以使用默认的。split()代替,以便它在任何空白上被分割。

最新更新