• python collection 和 heapq 模块使用说明


    一 :集合库collection

      python 拥有一些内置的数据类型,collections模块提供啦几个额外的数据类型:

        1,namedtuple   生成可以使用名字来访问元素内容的tuple子类

        2,deque  双端队列,可以加速从另一侧追加和推出对象

        3,counter  计数器,主要用来计数

        4,orderedDict 有序字典

        5,defaultdict 带有默认值的字典

      1)  namedtuple  命名的元祖形式,一般需要知道元祖里面每个字段代表什么含义,可以用命名元祖namedtuple

        

        继承命名的tuples 

        

      2)deque 双端队列

        deque最大的好处就是实现了从队列 头部快速增加和取出对象,比如popleft() 和appendleft()

        append()   appendleft()  pop()   popleft()   extend()   extendleft()  rotate()

        1,使用最多的就是限制队列长度,来获取队列的最后一个值或者几个值

          

         2) deque  的其他用法,可以参考下

           

       3)  Counter 计数器

          elements  返回一个迭代器,显示重复次数的元素,如果次数小于1,则被忽略

          most_common  获取出现次数最多的元素

          subtract   两个元素counter的元素进行相减 

            

          

          

          

        4) ordereddict  有序字典

        5)defaultdict  默认字典

    二 : heapd  堆队列

        

    heapq.heappush(heap, item)

    Push the value item onto the heap, maintaining the heap invariant.

    heapq.heappop(heap)

    Pop and return the smallest item from the heap, maintaining the heapinvariant. If the heap is empty,IndexError is raised. To access thesmallest item without popping it, use heap[0].

    heapq.heappushpop(heap, item)

    Push item on the heap, then pop and return the smallest item from the heap. The combined action runs more efficiently than heappush()followed by a separate call to heappop().

    heapq.nlargest(n, iterable, key=None)

    Return a list with the n largest elements from the dataset defined byiterable. key, if provided, specifies a function of one argument that isused to extract a comparison key from each element in the iterable:key=str.lower Equivalent to: sorted(iterable, key=key,reverse=True)[:n]

    heapq.nsmallest(n, iterable, key=None)

    Return a list with the n smallest elements from the dataset defined byiterable. key, if provided, specifies a function of one argument that isused to extract a comparison key from each element in the iterable:key=str.lower Equivalent to: sorted(iterable, key=key)[:n]

          

          

  • 相关阅读:
    查看线程
    shiro+多tomcat+redis实现session共享
    win11系统设置笔记本合盖上不休眠
    nvm切换node版本出现乱码 exit status 1:
    nvm安装vuecli
    SQL Server Management 2012 启动错误及解决:Cannot find one or more componets
    SQL Server 2012 连接 Oracle 11gR2 Database
    SQL Server 数据库跨区域时间问题
    SSIS 同步不同数据库的不同两张表
    Reporting Service 不能发送订阅报表的问题
  • 原文地址:https://www.cnblogs.com/1204guo/p/8520887.html
Copyright © 2020-2023  润新知