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

    python创建堆的方法有哪些

    小妮浅浅小妮浅浅2021-05-31 09:44:15原创2555

    1、说明

    创建堆有两种基本方法:heappush() 和 heapify()。

    当使用heappush()时,当新元素添加时,堆得顺序被保持了。

    如果数据已经在内存中,则使用 heapify() 来更有效地重新排列列表中的元素。

    2、实例

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    import heapq

    from heapq_showtree import show_tree

    from heapq_heapdata import data

      

    heap = []

    print('random :', data)

    print()

      

    for n in data:

        print('add {:>3}:'.format(n))

        heapq.heappush(heap, n)

        show_tree(heap)

         

    # output

    # random : [19, 9, 4, 10, 11]

    #

    # add  19:

    #

    #                  19

    # ------------------------------------

    #

    # add   9:

    #

    #                  9

    #         19

    # ------------------------------------

    #

    # add   4:

    #

    #                  4

    #         19                9

    # ------------------------------------

    #

    # add  10:

    #

    #                  4

    #         10                9

    #     19

    # ------------------------------------

    #

    # add  11:

    #

    #                  4

    #         10                9

    #     19       11

    # ------------------------------------

    以上就是python创建堆的两种方法,希望对大家有所帮助。更多Python学习指路:python基础教程

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

    专题推荐:python创建堆
    上一篇:python heapq是什么 下一篇:python删除堆中元素的方法

    相关文章推荐

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

    全部评论我要评论

    © 2021 Python学习网 苏ICP备16018502号-40

  • 取消发布评论
  • 

    Python学习网