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

275次阅读
没有评论
如何使用py​thon3中的heapq模块?

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

模块安装:

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

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-18发表,共计367字。
新手QQ群:570568346,欢迎进群讨论 Python51学习