python 计数器类Counter的用法

简单操作:

import collections
A=['a','b','b','c','d','b','a']
count=collections.Counter(A)
print(count)
Counter({'b': 3, 'a': 2, 'c': 1, 'd': 1})
count.items()
Out[6]: dict_items([('a', 2), ('b', 3), ('c', 1), ('d', 1)])
count.keys()
Out[7]: dict_keys(['a', 'b', 'c', 'd'])
count.values()
Out[8]: dict_values([2, 3, 1, 1])
count.elements()
Out[9]: <itertools.chain at 0x7f08050d66a0>
list(count.elements())
Out[10]: ['a', 'a', 'b', 'b', 'b', 'c', 'd']

排序:

Out[20]: [1, 1, 2, 3]
sorted(count.items())
Out[21]: [('a', 2), ('b', 3), ('c', 1), ('d', 1)]
sorted(count.items(),key=lambda x:x[1])
Out[22]: [('c', 1), ('d', 1), ('a', 2), ('b', 3)]

 

posted @ 2019-03-17 04:23  周洋  阅读(13729)  评论(0编辑  收藏  举报