默认最小在最前,这个和sorted一样,没有reverse,但是可以用tuple来玩
heapq是module(文件),所以import
heapq.heappush是直接调用这个module最外层的函数
import heapq
h1 = []
heapq.heappush(h1, (5, 'write code'))
heapq.heappush(h1, (7, 'release product'))
heapq.heappush(h1, (1, 'write spec'))
heapq.heappush(h1, (3, 'create tests'))
print(heapq.heappop(h1))
#(1, 'write spec')
h2 = [(7,'7'),(6,'6'),(5,'5'),(4,'4'),(3,'3'),(2,'2'),(1,'1')]
heapq.heapify(h2)
print(h2)
#[(1, '1'), (3, '3'), (2, '2'), (4, '4'), (6, '6'), (7, '7'), (5, '5')]
-------------------------
来个LeetCode题目玩一玩,涉及到Python的重载:
from collections import Counter
import heapq
class FreqWord:
def __init__(self, word, freq):
self.word, self.freq = word, freq
def __lt__(self, other):
if (self.freq != other.freq):
return self.freq < other.freq
else:
return self.word > other.word
class Solution:
def topKFrequent(self, words: List[str], k: int) -> List[str]:
cw = Counter(words)
heap = []
for word, freq in cw.items():
heapq.heappush(heap, FreqWord(word, freq))
if len(heap) > k:
retire = heapq.heappop(heap)
heap.sort(reverse=True)
return [x.word for x in heap]

本文深入探讨了Python中heapq模块的使用方法,包括如何利用heapq.heappush和heapq.heappop进行堆操作,以及如何通过heapq.heapify将列表转换为堆。此外,还介绍了一个LeetCode题目示例,展示了如何自定义类并实现比较方法以满足特定需求。
1767

被折叠的 条评论
为什么被折叠?



