python中的Counter()计数器是一个容器对象,实现了对可迭代对象中元素的统计,以键值对形式存储,key代表元素,value代表元素的个数。
#!/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})
test_3 = dict(test_1)
print(test_3)
print(type(test_3))
{1: 2, 2: 2, 3: 3, 4: 2, 5: 5, 6: 1}
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]
for k, v in test_1.items():
print(k, v)
1 2
2 2
3 3
4 2
5 5
6 1
#!/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)]