Python数据结构常用模块:collections、heapq、operator、itertools

heapq

  堆是一种特殊的树形结构,通常我们所说的堆的数据结构指的是完全二叉树,并且根节点的值小于等于该节点所有子节点的值

                                                       

常用方法

heappush(heap,item) 往堆中插入一条新的值
heappop(heap) 从堆中弹出最小值
heapreplace(heap,item) 从堆中弹出最小值,并往堆中插入item
heappushpop(heap,item) Python3中的heappushpop更高级
heapify(x) 以线性时间将一个列表转化为堆
merge(*iterables,key=None,reverse=False) 合并对个堆,然后输出
nlargest(n,iterable,key=None) 返回可枚举对象中的n个最大值并返回一个结果集list
nsmallest(n,iterable,key=None) 返回可枚举对象中的n个最小值并返回一个结果集list

常用方法示例 

#coding=utf-8

import heapq
import random def test():
li = list(random.sample(range(100),6))
print (li) n = len(li)
#nlargest
print ("nlargest:",heapq.nlargest(n, li))
#nsmallest
print ("nsmallest:", heapq.nsmallest(n, li))
#heapify
print('original list is', li)
heapq.heapify(li)
print('heapify list is', li)
# heappush & heappop
heapq.heappush(li, 105)
print('pushed heap is', li)
heapq.heappop(li)
print('popped heap is', li)
# heappushpop & heapreplace
heapq.heappushpop(li, 130) # heappush -> heappop
print('heappushpop', li)
heapq.heapreplace(li, 2) # heappop -> heappush
print('heapreplace', li)

  >>> [15, 2, 50, 34, 37, 55]
  >>> nlargest: [55, 50, 37, 34, 15, 2]
  >>> nsmallest: [2, 15, 34, 37, 50, 55]
  >>> original list is [15, 2, 50, 34, 37, 55]
  >>> heapify  list is [2, 15, 50, 34, 37, 55]
  >>> pushed heap is [2, 15, 50, 34, 37, 55, 105]
  >>> popped heap is [15, 34, 50, 105, 37, 55]
  >>> heappushpop [34, 37, 50, 105, 130, 55]
  >>> heapreplace [2, 37, 50, 105, 130, 55]

堆排序示例 

  heapq模块中有几张方法进行排序:

  方法一:

#coding=utf-8

import heapq

def heapsort(iterable):
heap = []
for i in iterable:
heapq.heappush(heap, i) return [heapq.heappop(heap) for j in range(len(heap))] if __name__ == "__main__":
li = [30,40,60,10,20,50]
print(heapsort(li))

  >>>> [10, 20, 30, 40, 50, 60]

  方法二(使用nlargest或nsmallest):

li = [30,40,60,10,20,50]
#nlargest
n = len(li)
print ("nlargest:",heapq.nlargest(n, li))
#nsmallest
print ("nsmallest:", heapq.nsmallest(n, li))

  >>> nlargest: [60, 50, 40, 30, 20, 10]
  >>> nsmallest: [10, 20, 30, 40, 50, 60]

  方法三(使用heapify):

def heapsort(list):
heapq.heapify(list)
heap = [] while(list):
heap.append(heapq.heappop(list)) li[:] = heap
print (li) if __name__ == "__main__":
li = [30,40,60,10,20,50]
heapsort(li)

  >>> [10, 20, 30, 40, 50, 60]

堆在优先级队列中的应用

  需求:实现任务的添加,删除(相当于任务的执行),修改任务优先级

pq = []                         # list of entries arranged in a heap
entry_finder = {} # mapping of tasks to entries
REMOVED = '<removed-task>' # placeholder for a removed task
counter = itertools.count() # unique sequence count def add_task(task, priority=0):
'Add a new task or update the priority of an existing task'
if task in entry_finder:
remove_task(task)
count = next(counter)
entry = [priority, count, task]
entry_finder[task] = entry
heappush(pq, entry) def remove_task(task):
'Mark an existing task as REMOVED. Raise KeyError if not found.'
entry = entry_finder.pop(task)
entry[-1] = REMOVED def pop_task():
'Remove and return the lowest priority task. Raise KeyError if empty.'
while pq:
priority, count, task = heappop(pq)
if task is not REMOVED:
del entry_finder[task]
return task
raise KeyError('pop from an empty priority queue')

  

Python常用数据结构之heapq模块的更多相关文章

  1. Python常用数据结构之collections模块

    Python数据结构常用模块:collections.heapq.operator.itertools collections collections是日常工作中的重点.高频模块,常用类型由: 计数器 ...

  2. Python常用内置模块之xml模块

    xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言.从结构上,很像HTML超文本标记语言.但他们被设计的目的是不同的,超文本标记语言被设计用来显示 ...

  3. Python常用的内建模块

    PS:Python之所以自称“batteries included”,就是因为内置了许多非常有用的模块,无需额外安装和配置,即可直接使用.下面就来看看一些常用的内建模块. 参考原文 廖雪峰常用的内建模 ...

  4. python常用数据结构讲解

    一:序列     在数学上,序列是被排成一排的对象,而在python中,序列是最基本的数据结构.它的主要特征为拥有索引,每个索引的元素是可迭代对象.都可以进行索引,切片,加,乘,检查成员等操作.在py ...

  5. python常用数据结构(1)

    python中有四种最常用的数据结构,分别是列表(list),字典(dict),集合(set)和元组(tuple) 下面简单描述下它们的区别和联系 1.初始化 不得不说,python数据结构的初始化比 ...

  6. Python常用数据结构(列表)

    Python中常用的数据结构有序列(如列表,元组,字符串),映射(如字典)以及集合(set),是主要的三类容器 内容 序列的基本概念 列表的概念和用法 元组的概念和用法 字典的概念和用法 各类型之间的 ...

  7. python 常用数据结构使用

    python 字典操作 http://www.cnblogs.com/kaituorensheng/archive/2013/01/24/2875456.html python 字典排序 http:/ ...

  8. python常用数据结构的常用操作

    作为基础练习吧.列表LIST,元组TUPLE,集合SET,字符串STRING等等,显示,增删,合并... #===========List===================== shoplist ...

  9. python常用数据结构

    0. 字典初始化 d = {'a':1,'b':2} 或 d={} d['a'] = 1 d['b'] = 2 是不是和json格式数据很相似,语法和JavaScript又很相似 1. 变量接受序列分 ...

随机推荐

  1. Windows和Linux如何使用Java代码实现关闭进程

    在用selenium做自动化测试时,由于各种不明原因,有时Chrome浏览器会出现假死的情况,也就是整个浏览器响应超时,本人脚本主要部署在Windows机器上,所以主要以Windows为主,浏览器为C ...

  2. TCP是什么? 最简单的三次握手说明

    TCP是什么? TCP(Transmission Control Protocol 传输控制协议)是一种面向连接(连接导向)的.可靠的. 基于IP的传输层协议.TCP在IP报文的协议号是6.TCP是一 ...

  3. scrapy_cookie禁用_延迟下载_自定义爬虫setting

    如何设置禁止cookie? 在setting中 添加字段: COOKIE_ENABLED = False                            # False关闭cookie,True ...

  4. Django 中 makemigrations、migrate时 No changes detected

    Django创建的项目中,需要更改.增加.删除表中的某些属性,性急直接把之前数据库表删除了,之后再执行: python manage.py makemigrations python manage.p ...

  5. C语言学习之选择排序

    上一篇文章中讲C语言排序中的比较常见的(交换)冒泡排序,那么这篇文章也将以新手个人的经历来讲同样比较常见而实用的数组排序之选择排序. 选择排序,从字面上看是通过选择来进行排序.其实它的用法就是通过选择 ...

  6. 【转】GPS连续运行单参考站解决方案

    GPS连续运行单参考站解决方案   一.  前言 随着国家信息化程度的提高及计算机网络和通信技术的飞速发展,电子政务.电子商务.数字城市.数字省区和数字地球的工程化和现实化,需要采集多种实时地理 空间 ...

  7. Hyperledger Fabric Endorsement policies——背书策略

    背书策略 背书策略用于指导peer如何确定交易是否得到了的认可.当一个peer接收到一个事务时,它会调用与事务的Chaincode相关联的VSCC(验证系统链代码),作为事务验证流程的一部分,以确定交 ...

  8. Git 生成 SSH 公钥

    2018-01-05 11:24:04 许多 Git 服务器都使用 SSH 公钥进行认证. 为了向 Git 服务器提供 SSH 公钥,如果某系统用户尚未拥有密钥,必须事先为其生成一份. 这个过程在所有 ...

  9. 基于Java的Arc Engine二次开发的环境的配置

    1.软件准备 ArcGIS for Desktop 10.2, Arc engine, jdk-7u60-windows-i586,Eclipse Mar2 2.软件的安装 2.1 ArcGIS fo ...

  10. Spring整合JMS(一)-基础篇

    1.基础知识 图1   同步通信和异步通信通信过程示意图 RMI使用的是同步通信,JMS使用的是异步通信.从图1可以看出异步通信的好处就是减少了不必要的等待,提高了效率. JMS中有两个主要的概念:消 ...