python collections

#collections 模块
#Counter 计数器,生成一个类字典类型
from collections import Counter
str="abcbcaccbbad"
#统计数量
dcamd=Counter(str)
print(dcamd)
'''
打印:Counter({'b': 4, 'c': 4, 'a': 3, 'd': 1})
'''
#按数量排序返回
print(dcamd.most_common(2))
'''
打印:[('b', 4), ('c', 4)]
'''
#将其value置为0
dcamd.subtract({'c': 4})
print(dcamd)
'''
打印:Counter({'b': 4, 'a': 3, 'd': 1, 'c': 0})
'''
#返回所有元素
print(list(dcamd.elements()))
'''
打印:['a', 'a', 'a', 'b', 'b', 'b', 'b', 'd']
'''
posted @ 2021-02-20 10:14  HunterSniper  阅读(61)  评论(0编辑  收藏  举报