更新时间:2021-12-06 08:53:07
有一个名为 collections.Counter
的专用类来执行这样的任务:
There is dedicated class named collections.Counter
to perform such tasks:
import collections
words = "hey hey hello"
c = collections.Counter(words.split())
print c # Counter({'hey': 2, 'hello': 1})
明确的解决方案是这样的:
Explicit solution would be something like this:
wordsCount = {}
words = [] # list of words
for word in words:
if word not in wordsCount:
wordsCount[word] = 0
wordsCount[word] += 1