collections.Counter
计数器
# 统计词频
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
result = {}
for color in colors:
if result.get(color)==None:
result[color]=1
else:
result[color]+=1
print (result)
#{'red': 2, 'blue': 3, 'green': 1}
# Counter
from collections import Counter
color_count = Counter(colors)
print(color_count)
print(dict(color_count))
output:
Counter({'blue': 3, 'red': 2, 'green': 1})
{'red': 2, 'blue': 3, 'green': 1}
# 获得所有元素
list(color_count.elements()
output:
['red', 'red', 'blue', 'blue', 'blue', 'green']
# 频率最高的n个元素
color_count.most_common(1)
output:
[('blue', 3)]