我尝试在不使用计数器的情况下,通过比较for循环中的每个字符串来打印列表中字符串的频率.请帮我做这个


longtext=input()
x=longtext.split(" ")
freq=1
for i in range(0,(len(x)-1)):
for j in range(i+1,len(x)):
if(x[j]==x[i]):
freq=freq+1
print(x[i],freq)

输入:hello world karteek karteek hello输出:你好2karteek 3

您可以使用defaultdict

from collections import defaultdict
d = defaultdict(int)
phrase = "hello world karteek karteek hello"
for word in phrase.split(" "):
d[word] += 1
print(d)
defaultdict(<class 'int'>, {'hello': 2, 'world': 1, 'karteek': 2})

最新更新