我在python中有一个列表,其中包含许多名称,我想打印出每个名称出现的次数

时间:2013-06-11 13:40:10

标签: python list sorting

例如:

list = ['herp' , 'derp', 'foo' , 'derp', 'foo', 'foo' , 'foo']

我希望能够获取此代码,以便我可以打印出来:

herp occurs 1 times.
derp occurs 2 times.
foo occurs 4 times.

最好的方法是什么?

3 个答案:

答案 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)

使用collections.Counter

from collections import Counter

Counter(['herp' , 'derp', 'foo' , 'derp', 'foo', 'foo' , 'foo'])
# Counter({'foo': 4, 'derp': 2, 'herp': 1})

答案 2 :(得分:0)

浏览列表并构建名称字典,并为每个字典条目增加一个计数器,查看您遇到名称的次数。