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)]

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM