zoukankan      html  css  js  c++  java
  • 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]

          

          

  • 相关阅读:
    poj 3625 Building Roads(最小生成树,二维坐标,基础)
    poj 2031 Building a Space Station(最小生成树,三维,基础)
    poj 2485 Highways(最小生成树,基础,最大边权)
    POJ 2349 Arctic Network(最小生成树,第k大边权,基础)
    hdu 1242 Rescue(BFS,优先队列,基础)
    POJ 1258 Agri-Net(最小生成树,基础)
    Redhat修改语言
    Rdesktop
    CentOS/Redhat VNC 服务
    RHCS配置web高可用集群
  • 原文地址:https://www.cnblogs.com/1204guo/p/8520887.html
Copyright © 2011-2022 走看看