python中heapq的用法(最小堆)

最小heap:parents总不大于children,根节点就是家族里最小的那位
python中heapq的用法(最小堆)_第1张图片

import heapq

lst = [1,2,3,5,1,5,8,9,6]

'''
一秒变成堆
'''
heapq.heapify(lst)
[1, 1, 3, 5, 2, 5, 8, 9, 6]

'''
最小的(顶端)再见
'''
heapq.heappop(lst)
[1, 2, 3, 5, 6, 5, 8, 9]

'''
最小的滚蛋,新人进入
'''
heapq.heapreplace(lst,99)
[2, 5, 3, 9, 6, 5, 8, 99]

'''
新人比最小的大,新人进入;若否,则不管
'''
heapq.heappushpop(lst,1)
[2, 5, 3, 9, 6, 5, 8, 99]

heapq.heappushpop(lst,66)
[3, 5, 5, 9, 6, 66, 8, 99]

'''
最大的n个是谁;
最小的n个是谁;
'''
print(heapq.nlargest(3,lst))
[99, 66, 9]
print(heapq.nsmallest(3,lst))
[3, 5, 5]

'''
合并
'''
lst1 = [100,101]
lst2 = [3, 5, 5, 9, 6, 66, 8, 99]
lst = list(heapq.merge(lst1,lst2))
[3, 5, 5, 9, 6, 66, 8, 99, 100, 101]

你可能感兴趣的:(tricks)