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']   按照你指定的个数重复字符串
     
     
     

      

  • 相关阅读:
    indy 發郵件的一些說明
    一此常用三方组件的地址(持续更新)
    oraSession直连
    获取关机信息及键盘或鼠标无响应的时长
    DBConnection释放说明
    发送邮件
    文件操作
    plsql中的一些知識
    TNativeXML用法(轉)
    redux中createStore, conbineReducers的简易封装
  • 原文地址:https://www.cnblogs.com/594504110python/p/9709492.html
Copyright © 2011-2022 走看看