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]

          

          

  • 相关阅读:
    cad是什么意思?教你快速把cad转换成pdf格式
    为什么街上的商贩更喜欢用微信支付,而不是支付宝,看完长知识了
    音乐剪辑软件怎么用?教你一个快速编辑音频的方法
    电脑如何录制视频?安利两种电脑录屏的方法
    被称为逆天改命的5大中国工程,曾轰动世界,你知道几个?
    如何使用音乐格式转换器?快速编辑音频文件的方法
    PPT结尾只会说“谢谢”?学会这些PPT结尾,观众主动为你鼓掌
    经典PHP面试题(冒泡排序),当场就被打脸,卧槽什么冒泡?为啥还排序?
    千万不要再搞混了,函数empty( var );输出的判断值是false : true
    PHP删除数组中空数组
  • 原文地址:https://www.cnblogs.com/1204guo/p/8520887.html
Copyright © 2011-2022 走看看