1、使用heappop()删除具有最小值的元素。
import heapq from heapq_showtree import show_tree from heapq_heapdata import data print('random :', data) heapq.heapify(data) print('heapified :') show_tree(data) print() for i in range(2): smallest = heapq.heappop(data) print('pop {:>3}:'.format(smallest)) show_tree(data) # output # random : [19, 9, 4, 10, 11] # heapified : # # 4 # 9 19 # 10 11 # ------------------------------------ # # # pop 4: # # 9 # 10 19 # 11 # ------------------------------------ # # pop 9: # # 10 # 11 19 # ------------------------------------
2、要删除现有元素,并在一次操作中用新值替换它们,使用heapreplace()。
import heapq from heapq_showtree import show_tree from heapq_heapdata import data heapq.heapify(data) print('start:') show_tree(data) for n in [0, 13]: smallest = heapq.heapreplace(data, n) print('replace {:>2} with {:>2}:'.format(smallest, n)) show_tree(data) # output # start: # # 4 # 9 19 # 10 11 # ------------------------------------ # # replace 4 with 0: # # 0 # 9 19 # 10 11 # ------------------------------------ # # replace 0 with 13: # # 9 # 10 19 # 13 11 # ------------------------------------
以上就是python删除堆中元素的方法,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。