python heapq堆排序高阶用法
python heapq相关操作
heapq 的一些常用方法:
-
heapify(list)
将列表转换为小根堆的数据结构。 -
heappush(heap, x)
,将 x 加入堆中。 -
heappop(heap)
,从堆中弹出最小的元素。 -
heapreplace(heap, x)
,弹出最小的元素,并将 x 加入堆中。 -
heappushpop(heap, x)
,先把 x 加入堆中,再弹出最小的元素。 -
heapq.nlargest(n, heap)
,返回 heap 中前 n 个最大的元素。 -
heapq.nsmallest(n, heap)
,返回 heap 中前 n 个最小的元素。
如何自定义堆排序?
重写__lt__方法
import heapq
a = range(10)
class Node:
def __init__(self, v):
self.v = v
def __lt__(self, other):
# 自定义lt便可实现大顶堆
return self.v > other.v
h = []
for i in a:
heapq.heappush(h, Node(i))
ans = heapq.nsmallest(len(h), h)
for i in ans:
print(i.v)
a = [(1, 'asd', 2), (2, 'asd', 2), (1, 'asd', 3), (5, 'asd', 3), (1, 'fd', 3)]
# 对于a想要按照第一个数从大到小,第二个字符串从大到小,第三个数字从小到大排序
class Node:
def __init__(self, v):
self.a, self.b, self.c = v[0], v[1], v[2]
def __lt__(self, other):
if self.a != other.a:
return self.a > other.a
if self.b != other.b:
return self.b > other.b
return self.c < other.c
h = []
for i in a:
heapq.heappush(h,Node(i))
ans = heapq.nsmallest(len(h),h)
for i in ans:
print(i.a,i.b,i.c)
# 5 asd 3
# 2 asd 2
# 1 fd 3
# 1 asd 2
# 1 asd 3
利用itemgetter
from operator import itemgetter
import heapq
list1 = [1, 6, 4, 3, 9, 5]
list2 = ['12', 'a6', '4', 'c34', 'b9', '5']
list3 = [
{'name': 'jim', 'age': 23, 'price': 500},
{'name': 'mase', 'age': 23, 'price': 600},
{'name': 'tom', 'age': 25, 'price': 2000},
{'name': 'alice', 'age': 22, 'price': 300},
{'name': 'rose', 'age': 21, 'price': 2400},
]
print(heapq.nlargest(len(list1), list1))
print(heapq.nlargest(len(list2), list2))
print(heapq.nlargest(len(list3), list3, key=itemgetter('age', 'price')))
print(heapq.nsmallest(len(list1), list1))
print(heapq.nsmallest(len(list2), list2))
print(heapq.nsmallest(len(list3), list3, key=itemgetter('age', 'price')))
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析