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

常用方法示例 

  1. #coding=utf-8
  2.  
  3. import heapq
  4. import random
  5.  
  6. def test():
  7. li = list(random.sample(range(100),6))
  8. print (li)
  9.  
  10. n = len(li)
  11. #nlargest
  12. print ("nlargest:",heapq.nlargest(n, li))
  13. #nsmallest
  14. print ("nsmallest:", heapq.nsmallest(n, li))
  15. #heapify
  16. print('original list is', li)
  17. heapq.heapify(li)
  18. print('heapify list is', li)
  19. # heappush & heappop
  20. heapq.heappush(li, 105)
  21. print('pushed heap is', li)
  22. heapq.heappop(li)
  23. print('popped heap is', li)
  24. # heappushpop & heapreplace
  25. heapq.heappushpop(li, 130) # heappush -> heappop
  26. print('heappushpop', li)
  27. heapq.heapreplace(li, 2) # heappop -> heappush
  28. 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模块中有几张方法进行排序:

  方法一:

  1. #coding=utf-8
  2.  
  3. import heapq
  4.  
  5. def heapsort(iterable):
  6. heap = []
  7. for i in iterable:
  8. heapq.heappush(heap, i)
  9.  
  10. return [heapq.heappop(heap) for j in range(len(heap))]
  11.  
  12. if __name__ == "__main__":
  13. li = [30,40,60,10,20,50]
  14. print(heapsort(li))

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

  方法二(使用nlargest或nsmallest):

  1. li = [30,40,60,10,20,50]
  2. #nlargest
  3. n = len(li)
  4. print ("nlargest:",heapq.nlargest(n, li))
  5. #nsmallest
  6. print ("nsmallest:", heapq.nsmallest(n, li))

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

  方法三(使用heapify):

  1. def heapsort(list):
  2. heapq.heapify(list)
  3. heap = []
  4.  
  5. while(list):
  6. heap.append(heapq.heappop(list))
  7.  
  8. li[:] = heap
  9. print (li)
  10.  
  11. if __name__ == "__main__":
  12. li = [30,40,60,10,20,50]
  13. heapsort(li)

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

堆在优先级队列中的应用

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

  1. pq = [] # list of entries arranged in a heap
  2. entry_finder = {} # mapping of tasks to entries
  3. REMOVED = '<removed-task>' # placeholder for a removed task
  4. counter = itertools.count() # unique sequence count
  5.  
  6. def add_task(task, priority=0):
  7. 'Add a new task or update the priority of an existing task'
  8. if task in entry_finder:
  9. remove_task(task)
  10. count = next(counter)
  11. entry = [priority, count, task]
  12. entry_finder[task] = entry
  13. heappush(pq, entry)
  14.  
  15. def remove_task(task):
  16. 'Mark an existing task as REMOVED. Raise KeyError if not found.'
  17. entry = entry_finder.pop(task)
  18. entry[-1] = REMOVED
  19.  
  20. def pop_task():
  21. 'Remove and return the lowest priority task. Raise KeyError if empty.'
  22. while pq:
  23. priority, count, task = heappop(pq)
  24. if task is not REMOVED:
  25. del entry_finder[task]
  26. return task
  27. 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. Performance Testing 前期准备以及场景设计

    性能测试的session参加过几个,也查阅了很多相关的资料.年前被分配了测试任务,一直拖到现在,准备开始做的时候,才发现真的是不知道如何做起啊.今天和同事聊了一下,有很大启发.测试小白一枚,只分享一下 ...

  2. LINUX文件操作命令

    body, table{font-family: 微软雅黑} table{border-collapse: collapse; border: solid gray; border-width: 2p ...

  3. RocketMQ环境搭建(双master模式)

    介绍: 多Master模式,一个集群无Slave,全是Master,例如2个Master或者3个Master. 优点:配置简单,单个Master宕机或重启维护对应用无影响,在磁盘配置为RAID10时, ...

  4. sping中防止定时任务多处运行解决方法

    @Servicepublic class TimerJobService implements LzhTimerJobDao{ Logger logger = LoggerFactory.getLog ...

  5. webpack + vue

    开始之前 本文包含以下技术,文中尽量给与详细的描述,并且附上参考链接,读者可以深入学习: 1.webpack2.Vue.js3.npm4.ES6语法 前言 在对着产品高举中指怒发心中之愤后,真正能够解 ...

  6. Linux下MongoDB安装和配置详解

    1.下载安装包 将解压到/usr/local/mongodb 文件夹下 # mkdir /usr/local/mongodb # tar zxvf mongodb-linux-x86_64-3.2.9 ...

  7. NOI2001 食物链

    食物链 题目描述 动物王国中有三类动物 A,B,C,这三类动物的食物链构成了有趣的环形.A 吃 B,B 吃 C,C 吃 A. 现有 N 个动物,以 1 - N 编号.每个动物都是 A,B,C 中的一种 ...

  8. SpringMVC 参数绑定注解解析

    本文介绍了用于参数绑定的相关注解. 绑定:将请求中的字段按照名字匹配的原则填入模型对象. SpringMVC就跟Struts2一样,通过拦截器进行参数匹配. 代码在 https://github.co ...

  9. R-FCN论文翻译

    R-FCN论文翻译 R-FCN: Object Detection viaRegion-based Fully Convolutional Networks 2018.2.6   论文地址:R-FCN ...

  10. 使用facebook和twitter进行分享经验总结

    凤凰涅槃,浴火重生. 在传说当中,凤凰是人世间幸福的使者,每五百年,它就要背负着积累于在人间的所有痛苦和恩怨情仇,投身于熊熊烈火中自焚,以生命和美丽的终结换取人世的祥和与幸福.同样在肉体经受了巨大的痛 ...