python删除堆中元素的方法
发布时间:2024-08-21 22:18:33

1、使用heappop()删除具有最小值的元素。
importheapq
fromheapq_showtreeimportshow_tree
fromheapq_heapdataimportdata
print('random:',data)
heapq.heapify(data)
print('heapified:')
show_tree(data)
print()
foriinrange(2):
smallest=heapq.heappop(data)
print('pop{:>3}:'.format(smallest))
show_tree(data)
#output
#random:[19,9,4,10,11]
#heapified:
#
#4
#919
#1011
#------------------------------------
#
#
#pop4:
#
#9
#1019
#11
#------------------------------------
#
#pop9:
#
#10
#1119
#------------------------------------2、使用heapreplace()在一次操作中删除现有元素并用新值替换。
importheapq
fromheapq_showtreeimportshow_tree
fromheapq_heapdataimportdata
heapq.heapify(data)
print('start:')
show_tree(data)
fornin[0,13]:
smallest=heapq.heapreplace(data,n)
print('replace{:>2}with{:>2}:'.format(smallest,n))
show_tree(data)
#output
#start:
#
#4
#919
#1011
#------------------------------------
#
#replace4with:
#
#0
#919
#1011
#------------------------------------
#
#replace0with13:
#
#9
#1019
#1311
#------------------------------------以上是python删除堆中元素的方法,希望对大家有所帮助。更多多Python学习指导:基础教程python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。
下一篇 python创建堆的方法有哪些
