前任:
list = ['herp' , 'derp', 'foo' , 'derp', 'foo', 'foo' , 'foo']
我希望能够得到这个代码,以便我可以打印出来:
herp occurs 1 times.
derp occurs 2 times.
foo occurs 4 times.
最好的方法是什么?
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
from collections import Counter
Counter(['herp' , 'derp', 'foo' , 'derp', 'foo', 'foo' , 'foo'])
# Counter({'foo': 4, 'derp': 2, 'herp': 1})
遍历您的列表并构建一个名称字典,并为每个字典条目增加一个计数器,以记录您遇到该名称的次数。