Counter在python中两种用法

  • 更新时间:2021-08-04 09:18:23
  • 编辑:富陶然
给网友朋友们带来一篇相关的编程文章,网友益梦丽根据主题投稿了本篇教程内容,涉及到Python相关内容,已被726网友关注,相关难点技巧可以阅读下方的电子资料。

参考资料

正文内容

给大家整理一篇不错的python文章,代码实例很详细,把代码经过测试发布到这里,为了大家阅读方便。

Counter在python中两种用法

此映射类型为键准备了一个整数计数器。每更新一次键,该计数器就增加一次。因此,此类型可用于为可散列表对象计数,或将其作为多重集合使用——多重集合就是集合中的元素可以多次出现。

1、Counter 实现了 + 和 - 运算符用来合并记录,还有像 most_common([n]) 这类很有用的方法。most_common([n]) 会按照次序返回映射里最常见的 n 个键和它们的计数。

In [1]: from collections import Counter
 
In [2]: langs = ['java', 'php', 'python', 'C#', 'kotlin', 'swift', 'python']
 
In [3]: ct = Counter(langs)
 
In [4]: ct
Out[4]: Counter({'C#': 1, 'java': 1, 'kotlin': 1, 'php': 1, 'python': 2, 'swift': 1})
 
In [5]: ct.update(['java', 'c'])
 
In [6]: ct
Out[6]:
Counter({'C#': 1,
         'c': 1,
         'java': 2,
         'kotlin': 1,
         'php': 1,
         'python': 2,
         'swift': 1})
 
In [7]: ct.most_common(2)
Out[7]: [('java', 2), ('python', 2)]

2、直接操作字符串

In [9]: ct = Counter('abracadabra')
 
In [10]: ct
Out[10]: Counter({'a': 5, 'b': 2, 'c': 1, 'd': 1, 'r': 2})
 
In [11]: ct.update('aaaaazzz')
 
In [12]: ct
Out[12]: Counter({'a': 10, 'b': 2, 'c': 1, 'd': 1, 'r': 2, 'z': 3})
 
In [13]: ct.most_common(2)
Out[13]: [('a', 10), ('z', 3)]

以上就是Counter在python中两种用法,希望能对大家有所帮助,更多知识尽在python学习网。

相关教程

用户留言