创新互联Python教程:python创建堆的方法有哪些
1、说明

创新互联从2013年成立,是专业互联网技术服务公司,拥有项目成都网站建设、网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元大安市做网站,已为上家服务,为大安市各地企业和个人服务,联系电话:18980820575
创建堆有两种基本方法: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电脑。
网站名称:创新互联Python教程:python创建堆的方法有哪些
本文路径:http://jxruijie.cn/article/djoocjh.html

 
                