Har*_*rry 3 python string list count
我尝试解决此问题的方法是将用户的单词输入到列表中,然后使用.count()查看单词在列表中的次数.问题是每当出现平局时,我需要打印所有出现次数最多的单词.只有当我使用的单词不在另一个出现相同次数的单词内时,它才有效.例如:如果我按顺序使用吉米和吉姆,它只会打印吉米.
for value in usrinput:
dict.append(value)
for val in range(len(dict)):
count = dict.count(dict[val])
print(dict[val],count)
if (count > max):
max = count
common= dict[val]
elif(count == max):
if(dict[val] in common):
pass
else:
common+= "| " + dict[val]
Run Code Online (Sandbox Code Playgroud)
使用collections.Counter课程.我会给你一个提示.
>>> from collections import Counter
>>> a = Counter()
>>> a['word'] += 1
>>> a['word'] += 1
>>> a['test'] += 1
>>> a.most_common()
[('word', 2), ('test', 1)]
Run Code Online (Sandbox Code Playgroud)
您可以从此处提取单词和频率.
使用它从用户输入中提取频率.
>>> userInput = raw_input("Enter Something: ")
Enter Something: abc def ghi abc abc abc ghi
>>> testDict = Counter(userInput.split(" "))
>>> testDict.most_common()
[('abc', 4), ('ghi', 2), ('def', 1)]
Run Code Online (Sandbox Code Playgroud)