• 技术文章 >Python技术 >Python基础教程

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

    十一十一2021-04-13 10:30:10原创4438

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

    模块安装:

    1

    pip install heapq

    模块函数:

    1

    2

    nlargest()

    nsmallest()

    应用实例:

    实现堆排序

    1

    2

    3

    4

    5

    6

    7

    8

    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]))

    输出结果:

    1

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

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

    专题推荐:heapq模块
    上一篇:python中base64模块是什么? 下一篇:如何使用python中schedule模块?

    相关文章推荐

    • python中pygal模块如何使用?• python中base64模块是什么?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网