您现在的位置是:课程教程文章

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

2023-12-15 21:25课程教程文章 人已围观

 

本文教程操作环境: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模块到此就介绍完毕了,大家如果感兴趣的话,可以带入项目里学习了解哦~

课程教程:如何使用py​thon3中的heapq模块?

上一篇:如何使用python中schedule模块?

下一篇:没有了

站点信息

  • 文章统计篇文章