知行编程网知行编程网  2022-11-19 08:00 知行编程网 隐藏边栏  23 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python删除堆中元素的方法的相关知识,包括python删除列表重复元素,以及python增加列表元素这些编程知识,希望对大家有参考作用。

如何在python中从堆中删除元素


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
# ------------------------------------


本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享