我有一个赋值,如果我输入一个字符串,例如
food food games hi food
它会像这样打印出来:
food: 3
games: 1
hi: 1
我现在做的代码是
def count_word(string1):
counts = {}
words = string1.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
string1 = str(input())
print(count_word(string1))
如果输入与上面相同的字符串,则打印出:
{'food': 3, 'games': 1, 'hi': 1}
我该怎么做才能像这样打印出来:
food: 3
games: 1
hi: 1
发布于 2022-04-11 02:48:26
以下应起作用:
d = {'food': 3, 'games': 1, 'hi': 1} # generated by counter function
for word, count in d.items():
print(f'{word}: {count}')
如果要按字母顺序排序,请将d.items()
替换为sorted(d.items())
。
发布于 2022-04-11 02:49:44
dsic = {'food': 3, 'games': 1, 'hi': 1}
你也许可以试试这样的方法:
import json
print(json.dumps(dsic, sort_keys=False, indent=4))
或者这个:
for i,x in dsic.items():
print(str(i)+': ' + str(x))
发布于 2022-04-11 02:49:47
你应该做你的研究,然后再张贴在堆叠溢出。目前,提示是使用两个循环。一个用于列表,另一个用于打印字符串。
https://stackoverflow.com/questions/71826434
复制相似问题