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

    python删除堆中元素的方法

    小妮浅浅小妮浅浅2021-05-31 09:45:24原创3200

    1、使用heappop()删除具有最小值的元素。

    import heapq
    from heapq_showtree import show_tree
    from heapq_heapdata import data
     
    print('random    :', data)
    heapq.heapify(data)
    print('heapified :')
    show_tree(data)
    print()
     
    for i in range(2):
        smallest = heapq.heappop(data)
        print('pop    {:>3}:'.format(smallest))
        show_tree(data)
        
    # output
    # random    : [19, 9, 4, 10, 11]
    # heapified :
    #
    #                  4
    #         9                 19
    #     10       11
    # ------------------------------------
    #
    #
    # pop      4:
    #
    #                  9
    #         10                19
    #     11
    # ------------------------------------
    #
    # pop      9:
    #
    #                  10
    #         11                19
    # ------------------------------------

    2、要删除现有元素,并在一次操作中用新值替换它们,使用heapreplace()。

    import heapq
    from heapq_showtree import show_tree
    from heapq_heapdata import data
     
    heapq.heapify(data)
    print('start:')
    show_tree(data)
     
    for n in [0, 13]:
        smallest = heapq.heapreplace(data, n)
        print('replace {:>2} with {:>2}:'.format(smallest, n))
        show_tree(data)
        
    # output
    # start:
    #
    #                  4
    #         9                 19
    #     10       11
    # ------------------------------------
    #
    # replace  4 with  0:
    #
    #                  0
    #         9                 19
    #     10       11
    # ------------------------------------
    #
    # replace  0 with 13:
    #
    #                  9
    #         10                19
    #     13       11
    # ------------------------------------

    以上就是python删除堆中元素的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:python删除堆元素
    品易云
    上一篇:python创建堆的方法有哪些 下一篇:python是什么蛇

    相关文章推荐

    • python请求头如何自定义?• python中HTTP方法有哪些• python如何使用requests检查请求• python中contextmanager()的转换• python忽略异常的方法• python os.path如何解析路径• python heapq是什么• python创建堆的方法有哪些

    全部评论我要评论

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

  • 取消发布评论
  • 

    Python学习网