這篇文章將為大家詳細講解有關使用python怎么刪除堆中的元素,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
python常用的庫:1.requesuts;2.scrapy;3.pillow;4.twisted;5.numpy;6.matplotlib;7.pygama;8.ipyhton等。
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怎么刪除堆中的元素就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。