目录
对于序列如字符串str、列表list和tuple可以统计里面数据出现的次数。我们使用的是 collections 模块。
collections模块的常用方法有:
- 计数器(Counter)
- 双向队列(deque)
- 默认字典(defaultdict)
- 有序字典(OrderedDict)
- 可命名元组(namedtuple)
使用以上类型时需要导入模块 from collections import *
Counter
Counter()方法对传入的序列中出现的数据进行汇总,返回一个<class 'collections.Counter'>的对象
from collections import Counter
a="aabcac"
b=['a','a','b','c','a','c']
c=('a','a','b','c','a','c')
print(Counter(a),type(Counter(a)))
print(Counter(b))
print(Counter(c))
#######################################
Counter({'a': 3, 'c': 2, 'b': 1}) <class 'collections.Counter'>
Counter({'a': 3, 'c': 2, 'b': 1}