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

2025-12-01 0 42,575

 

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:以上部本文内容由互联网用户自发贡献,本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。投诉邮箱:3758217903@qq.com

ZhiUp资源网 python基础 如何使用py​thon3中的heapq模块? https://www.zhiup.top/2705.html

相关