• 技术文章 >Python技术 >Python基础教程

    Counter在python中两种用法

    小妮浅浅小妮浅浅2021-02-24 16:34:42原创6068

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

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

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    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、直接操作字符串

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    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学习网。

    专题推荐:python counter
    上一篇:python添加列表元素的多种方法 下一篇:python对列表进行永久性或临时排序的方法

    相关文章推荐

    • python中二叉树有哪些类型• python特征生成中字符类型有哪些?• python用生成器实现协程• python greenlet如何交替运行• python中Fearturetools三个基本概念• defaultdict在python中接收调用对象• python线程中deque如何使用?• python列表运算详解

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网