ITPub博客

首页 > IT职业 > IT职场 > 如何使用py​thon3中的heapq模块?

如何使用py​thon3中的heapq模块?

IT职场 作者:rainbows 时间:2021-09-11 10:03:38 0 删除 编辑

 

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

模块安装:

pip install heapq

模块函数:

nlargest()
nsmallest()

应用实例:

实现堆排序

from heapq import *
def heap_sort(iterable):
 h = []
 for value in iterable:
 heappush(h, value)
 return [heappop(h) for _ in range(len(h))]
if __name__ == '__main__':
print(heap_sort([1, 3, 5, 9, 2, 123, 4, 88]))

输出结果:

Output: [1, 2, 3, 4, 5, 9, 88, 123]

关于heapq模块到此就介绍完毕了,大家如果感兴趣的话,可以带入项目里学习了解哦~

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2442/viewspace-2831402/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-15

  • 博文量
    112
  • 访问量
    1268