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