1、counter
在python中是一个计数器。是dict的子类,计算可hash的对象。
主要功能:可以支持方便、快速的计数,将元素数量统计,然后计数并返回一个字典,键为元素,值为元素个数。
2、counter创建的四种方法:
>>> c = Counter() # 创建一个空的Counter类
>>> c = Counter('gallahad') # 从一个可iterable对象(list、tuple、dict、字符串等)创建
>>> c = Counter({'a': 4, 'b': 2}) # 从一个字典对象创建
>>> c = Counter(a=4, b=2) # 从一组键值对创建3、使用示例
计数的例子:统计一个文件中每个单词出现的次数
# 普通青年
d = {}
with open('/etc/passwd') as f:
for line in f:
for word in line.strip().split(':'):
if word not in d:
d[word] = 1
else:
d[word] += 1
# 文艺青年
d = defaultdict(int)
with open('/etc/passwd') as f:
for line in f:
for word in line.strip().split(':'):
d[word] += 1
# 棒棒的青年
word_counts = Counter()
with open('/etc/passwd') as f:
for line in f:
word_counts.update(line.strip().split(':'))