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-8import heapq
import randomdef test():li = list(random.sample(range(100),6))print (li)n = len(li)#nlargestprint ("nlargest:",heapq.nlargest(n, li))#nsmallestprint ("nsmallest:", heapq.nsmallest(n, li)) #heapifyprint('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-8import heapqdef 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[:] = heapprint (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 countdef 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] = entryheappush(pq, entry)def remove_task(task):'Mark an existing task as REMOVED.  Raise KeyError if not found.'entry = entry_finder.pop(task)entry[-1] = REMOVEDdef 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 taskraise KeyError('pop from an empty priority queue')

  

转载于:https://www.cnblogs.com/xiaobingqianrui/p/8487840.html

Python常用数据结构之heapq模块相关推荐

  1. python常用内置模块-Python常用内置模块之xml模块

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

  2. python常用内置模块-Python常用内置模块之xml模块(详解)

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

  3. python常用数据结构_Python常见数据结构整理

    Python 常见数据结构详解 这篇文章主要介绍了 Python 常见数据结构 , 需要的朋友可以参考下 本文详细罗列归纳了 Python 常见数据结构,并附以实例加以说明,相信对读者有一定的参 考借 ...

  4. [Python]常用数据结构 练习题

    常用数据结构 练习题 输人5个整数放到列表list1 中,输出下标及值,然后将列表listl 中大于平均值的元素组成一个新列表list2,输出平均值和列表list2.请利用列表推导式解决该问题. li ...

  5. python常用数据结构_Python入门: 数据结构大汇总

    一.列表 1.列表的创建 列表是有序集合,没有固定大小,能够保存任意数量任意类型的 Python 对象,语法为 [元素1, 元素2, ..., 元素n].关键点是 " 中括号 [ ]&quo ...

  6. python常用的日期时间模块

    今天.昨天.明天 import datetime today = datetime.date.today() # 今天 yesterday = today - datetime.timedelta(d ...

  7. Python内置的heapq模块的使用

    Python3.4版本中heapq包含了几个有用的方法: heapq.heappush(heap,item):将item,推入heap >>> items = [1,2,9,7,3] ...

  8. Python常用数据结构(列表、元组、字典、集合)

    列表: list1 = [1,'ans',2983,12,'Hello','nihao'] #一个列表中可以存放多个不同数据类型的值,例如上面例子中有数字也有字符串list1.append(" ...

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

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

最新文章

  1. 黄聪:第2章 并发操作的一致性问题 (2)
  2. Solr中Field常用属性
  3. ABAP程序相互调用--SUBMIT
  4. android sqlitejian监听,tencent/sqlite.md · zhoujian/AndroidInterView - Gitee.com
  5. SAP 电商云 Spartacus 产品明细页面的 OCC API 是如何被触发的
  6. SAP RFC 获取BDC 消息文本的实现
  7. putty连接linux上传python,通过PuTTY用于SSH的Python脚本
  8. Hbase具体操作(图文并茂且超超全~~~)
  9. 从零基础入门Tensorflow2.0 ----三、9.tf.function
  10. 基于SSM的停车位收费系统
  11. MSP432P401R学习:CCS入门实验练习,使用CCS新建、导入、编译、下载工程
  12. wap精武堂源码php_精武堂怎么学技能更牛?
  13. 《现代操作系统(中文第四版)》课后习题答案 第四章 文件系统
  14. 思维导图模板创意可爱简单,模板资源分享
  15. 怎么彻底卸载2345软件、怎么屏蔽2345弹窗
  16. 2021年中国化妆品发展现状及进出口状况分析:消费升级局面下,化妆品市场依旧景气 [图]
  17. 怎样用c语言制作文件保险箱,开题(电子保险箱)技巧.doc
  18. Mac系统 - zsh所有命令失效解决方式
  19. mac连接蓝牙耳机只有一个有声音
  20. 读书笔记-尖刀团队特训记

热门文章

  1. 根据选择计算Mask值
  2. Underscore.js Version (1.2.3) 中文文档
  3. 剑桥三星AI中心提出“X-ViT”:基于时空混合attention的视频Transformer,大幅度降低计算复杂度...
  4. ICCV2021 人脸深伪分析挑战赛 重磅来袭
  5. 基于深度学习的眼底影像分析最新综述
  6. 目标检测多模型集成方法总结
  7. 即插即用!视频超分中的涨点神器:iSeeBetter
  8. 组装式AI落地新模式,降低企业AI试错成本
  9. 如何简单有效地实现迁移学习?ECCV 2020 论文介绍
  10. 【python零基础入门学习】Python入门,带你快速学习为什么那么多人想学 Python?