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]

          

          

  • 相关阅读:
    Google Earth 使用的经纬度格式及转换
    ADO.NET Entity Framework 一个简单数据绑定例子
    Oracle 异常 ORA01861: literal does not match format string(字符串格式不匹配)
    备份和还原 甲方 Oracle 数据库 问题一大堆
    使用 xsd.exe 命令工具 将 xsd架构 生成 类文件
    简单的源代码统计工具(统计源代码行数、工数、成本、质量指标统计)
    Google KML 起步教程笔记(二)高级 KML 文档与MIME 类型
    SQL Server 2008 中的空间数据存储
    PowerCmd 很好用的命令行工具,也许大家早就知道。
    Google Earth 本地地图缓存文件路径和KML文件路径
  • 原文地址:https://www.cnblogs.com/1204guo/p/8520887.html
Copyright © 2011-2022 走看看