python中的Counter()计数器是一个容器对象,实现了对可迭代对象中元素的统计,以键值对形式存储,key代表元素,value代表元素的个数。
使用Counter()方法对元素计数,示例如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from collections import Counter
if __name__ == '__main__':
test_1 = Counter([1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 6])
test_2 = Counter("aabbccccddeeef")
print(test_1)
print(test_2)
print(type(test_1))
Counter({5: 5, 3: 3, 1: 2, 2: 2, 4: 2, 6: 1})
Counter({'c': 4, 'e': 3, 'a': 2, 'b': 2, 'd': 2, 'f': 1})
<class 'collections.Counter'>
使用dict()方法转换成字典:
test_3 = dict(test_1)
print(test_3)
print(type(test_3))
{1: 2, 2: 2, 3: 3, 4: 2, 5: 5, 6: 1}
<class 'dict'>
使用.keys()方法得到key值:
test_4 = test_1.keys()
print(test_4)
print(list(test_4))
dict_keys([1, 2, 3, 4, 5, 6])
[1, 2, 3, 4, 5, 6]
使用items()方法遍历输出:
for k, v in test_1.items():
print(k, v)
1 2
2 2
3 3
4 2
5 5
6 1
使用most_common()方法获取数目最多的前n个元素:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from collections import Counter
if __name__ == '__main__':
test_1 = Counter([1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 6])
print(test_1)
print(test_1.most_common(3))
Counter({5: 5, 3: 3, 1: 2, 2: 2, 4: 2, 6: 1})
[(5, 5), (3, 3), (1, 2)]