例如:
list = ['herp' , 'derp', 'foo' , 'derp', 'foo', 'foo' , 'foo']
我希望能够获取此代码,以便我可以打印出来:
herp occurs 1 times.
derp occurs 2 times.
foo occurs 4 times.
最好的方法是什么?
答案 0 :(得分:7)
使用collections.Counter()
object:
from collections import Counter
counts = Counter(lst)
for word, count in counts.most_common():
print '{} occurs {} times'.format(word, count)
这具有按频率对单词进行排序的良好副作用。如果您需要按字母顺序排序的单词,请对.items()
结果进行排序:
import operator
for word, count in sorted(counts.items(), key=operator.itemgetter(1)):
演示:
>>> lst = ['herp' , 'derp', 'foo' , 'derp', 'foo', 'foo' , 'foo']
>>> from collections import Counter
>>> counts = Counter(lst)
>>> for word, count in counts.most_common():
... print '{} occurs {} times'.format(word, count)
...
foo occurs 4 times
derp occurs 2 times
herp occurs 1 times
>>> import operator
>>> for word, count in sorted(counts.items(), key=operator.itemgetter(1)):
... print '{} occurs {} times'.format(word, count)
...
herp occurs 1 times
derp occurs 2 times
foo occurs 4 times
答案 1 :(得分:3)
from collections import Counter
Counter(['herp' , 'derp', 'foo' , 'derp', 'foo', 'foo' , 'foo'])
# Counter({'foo': 4, 'derp': 2, 'herp': 1})
答案 2 :(得分:0)
浏览列表并构建名称字典,并为每个字典条目增加一个计数器,查看您遇到名称的次数。