栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

堆(heap)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

堆(heap)

堆(heap)
又被为优先队列(priority queue)。

python的heapq模块默认的是最小堆。堆数据结构最重要的特征是heap[0] 永远是最小的元素。

8个headq函数:

import heapq

将item压入堆heqp中。
list1 = [1, 3, 5, 2, 6, 8, 9, 3]
heapq.heappush(list1, 12)

从堆item弹出最小值。
list1 = [1, 3, 5, 2, 6, 8, 9, 3]
heapq1 = heapq.heappop(list1)

heapq.heapify(list):参数必须是list,此函数必须将list变成堆,实时操作。
list1 = [1, 3, 5, 2, 6, 8, 9, 3]
heapq1 = heapq.heapify(list1)

heappushpop(heap, item): heappush方法和heappop方法的合体,先heappush(heap, item),再heappop(heap)

heapreplace(heap, item): heappop方法和heappush方法的合体,先heappop(heap),再heappush(heap, item)

将多个堆进行合并
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
new_heapq = heapq.merge(list1, list2)

获取iterable中最大的n个值
list1 = [1, 3, 5, 7, 2, 4, 6, 8]
print(heapq.nlargest(2, list1))

获取iterable中最大的n个值
list1 = [1, 3, 5, 7, 2, 4, 6, 8]
print(heapq.nsmallest(2, list1))
 

参考

python模块之heapq模块 - 掘金

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/858853.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号