zl程序教程

您现在的位置是:首页 >  Python

当前栏目

python创建堆的方法有哪些

2023-03-20 15:29:40 时间

python创建堆的方法有哪些

1、说明

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

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

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

2、实例

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电脑。