zoukankan      html  css  js  c++  java
  • collections模块的使用

     1. Counter

      counter是collections中的一个模块, 它能够统计出字符串/文本中的每一个元素出现的次数, 并可以对结果进行进一步的处理.

      使用方法

      传入: 字符串

      默认返回: Counter对象的字典

    text = """
    Django is a high-level Python Web 
    framework that encourages rapid 
    development and clean, pragmatic design. 
    Built by experienced developers, 
    it takes care of much of the hassle of Web development, 
    so you can focus on writing your app without needing to reinvent the wheel. 
    It’s free and open source.
    """
    from collections import Counter
    c = Counter(text.replace(" ", ""))
    print(c)

      默认不调用任何方法时会返回每一个元素出现的次数, 并以键值对的方式返回, {元素, 次数}, 返回的结果按照元素出现的次数从大到小依次排序

      

    most_common()方法
    from collections import Counter
    c = Counter(text.replace(" ", "")).most_common(3)
    print(c)
    # [('e', 37), ('o', 19), ('n', 18)]
    most_common()接受一个int类型, 用来从结果中将前三个元素的同级结果输出, 返回的是一个真正的列表

    .elements()方法
    c = Counter(A=4, Y=2, Q=1)
    print(c.elements())
    # <itertools.chain object at 0x00000000021BA0B8>  返回的是一个可迭代对象
    print(list(c.elements()))
    # ['A', 'A', 'A', 'A', 'Y', 'Y', 'Q']   按照你指定的个数重复字符串
     
     
     

      

  • 相关阅读:
    新浪推出开放云计算平台Sina App Engine
    摄像机标定
    Qt开发环境大全
    [转]卡尔曼滤波器
    Qt Creator:跨平台 IDE
    建立交叉编译的Qt/Embeded开发环境
    Linux mmap
    QtCreator在不同平台开发的程序的运行
    粒子滤波概述
    13、几点小结,unsigned long long
  • 原文地址:https://www.cnblogs.com/594504110python/p/9709492.html
Copyright © 2011-2022 走看看