如何使用python计数模块counter?

546次阅读
没有评论

如何使用python计数模块counter?

如何使用python计数模块counter?

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(':'))

以上就是对计数模块counter的介绍,counter方便、快速的帮助我们计算,上面的使用方法要掌握哦~

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-17发表,共计882字。
新手QQ群:570568346,欢迎进群讨论 Python51学习