Python collections模块之Counter()详解
[*]计数器(Counter)
dict的子类,计算可hash的对象
请点击Counter
Counter()主要功能:可以支持方便、快速的计数,将元素数量统计,然后计数并返回一个字典,键为元素,值为元素个数。
from collections import Counter
list1 = ["a", "a", "a", "b", "c", "c", "f", "g", "g", "g", "f"]
dic = Counter(list1)
print(dic)
#结果:次数是从高到低的
#Counter({'a': 3, 'g': 3, 'c': 2, 'f': 2, 'b': 1})
print(dict(dic))
#结果:按字母顺序排序的
#{'a': 3, 'b': 1, 'c': 2, 'f': 2, 'g': 3}
print(dic.items()) #dic.items()获取字典的key和value
#结果:按字母顺序排序的
#dict_items([('a', 3), ('b', 1), ('c', 2), ('f', 2), ('g', 3)])
print(dic.keys())
#结果:
#dict_keys(['a', 'b', 'c', 'f', 'g'])
print(dic.values())
#结果:
#dict_values()
print(sorted(dic.items(), key=lambda s: (-s)))
#结果:按统计次数降序排序
#[('a', 3), ('g', 3), ('c', 2), ('f', 2), ('b', 1)]
for i, v in dic.items():
if v == 1:
print(i)
#结果:
#b
页:
[1]