counter计数器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了counter计数器相关的知识,希望对你有一定的参考价值。
import collections c1 = collections.Counter("aaaabbbbcccjjj") print(type(c1)) print(c1,‘\n‘) """ <class ‘collections.Counter‘> Counter({‘a‘: 4, ‘b‘: 4, ‘c‘: 3, ‘j‘: 3}) """ #增加和删除 c1.update("xxwc") print(c1,‘\n‘) #Counter({‘a‘: 4, ‘b‘: 4, ‘c‘: 4, ‘j‘: 3, ‘x‘: 2, ‘w‘: 1}) c1.subtract("a") print(c1,‘\n‘) #Counter({‘b‘: 4, ‘c‘: 4, ‘a‘: 3, ‘j‘: 3, ‘x‘: 2, ‘w‘: 1}) #返回前面3个元素。返回的是列表 ret = c1.most_common(3) print(ret) print(type(ret),‘\n‘) #[(‘b‘, 4), (‘c‘, 4), (‘a‘, 3)] #<class ‘list‘> #遍历c1的元素 for item in c1.elements(): print(item) print(‘\n‘) for k,v in c1.items(): print(k,v) print(type(k),type(v)) print(‘\n‘) """ a 3 <class ‘str‘> <class ‘int‘> b 4 <class ‘str‘> <class ‘int‘> c 4 <class ‘str‘> <class ‘int‘> """ for k in c1.keys(): print(k) """ a b c j x w """
有序字典
d1 = collections.OrderedDict() d1[‘k3‘] = ‘v3‘ d1[‘k1‘] = ‘v1‘ d1[‘k2‘] = ‘v2‘ print(d1)
OrderedDict([(‘k3‘, ‘v3‘), (‘k1‘, ‘v1‘), (‘k2‘, ‘v2‘)])
默认字典
创建默认字典的时候必须要给一个值的类型
d2 = collections.defaultdict(list) d2[‘k1‘].append(‘v1‘) print(d2)
defaultdict(<class ‘list‘>, {‘k1‘: [‘v1‘]})
以上是关于counter计数器的主要内容,如果未能解决你的问题,请参考以下文章