当前位置:   article > 正文

Python heapq模块

python heapq heappush

这个模块(build-in)实现了一个堆的数据结构,完美的解决了Top-K问题,以后解决Top-K问题的时候,直接把这个模块拿来用就可以了

注意,默认的heap是一个小顶堆!

 

heapq模块提供了如下几个函数:

 

heapq.heappush(heap, item) 把item添加到heap中(heap是一个列表)

heapq.heappop(heap) 把堆顶元素弹出,返回的就是堆顶

heapq.heappushpop(heap, item) 先把item加入到堆中,然后再pop,比heappush()再heappop()要快得多

heapq.heapreplace(heap, item) 先pop,然后再把item加入到堆中,比heappop()再heappush()要快得多

heapq.heapify(x) 将列表x进行堆调整,默认的是小顶堆

heapq.merge(*iterables) 将多个列表合并,并进行堆调整,返回的是合并后的列表的迭代器

heapq.nlargest(n, iterable, key=None) 返回最大的n个元素(Top-K问题)

heapq.nsmallest(n, iterable, key=None) 返回最小的n个元素(Top-K问题)

 

下面看下示例:

 

  1. import heapq
  2. import random
  3. # Top-K
  4. mylist = list(random.sample(range(100), 10))
  5. k = 3
  6. largest = heapq.nlargest(k, mylist)
  7. smallest = heapq.nsmallest(k, mylist)
  8. print('original list is', mylist)
  9. print('largest-'+str(k), ' is ', largest)
  10. print('smallest-'+str(k), ' is ', smallest)
  11. # heapify
  12. print('original list is', mylist)
  13. heapq.heapify(mylist)
  14. print('heapify list is', mylist)
  15. # heappush & heappop
  16. heapq.heappush(mylist, 105)
  17. print('pushed heap is', mylist)
  18. heapq.heappop(mylist)
  19. print('popped heap is', mylist)
  20. # heappushpop & heapreplace
  21. heapq.heappushpop(mylist, 130) # heappush -> heappop
  22. print('heappushpop', mylist)
  23. heapq.heapreplace(mylist, 2) # heappop -> heappush
  24. print('heapreplace', mylist)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

输出结果为:

  1. original list is [18, 6, 10, 24, 48, 2, 9, 25, 16, 89]
  2. largest-3 is [89, 48, 25]
  3. smallest-3 is [2, 6, 9]
  4. original list is [18, 6, 10, 24, 48, 2, 9, 25, 16, 89]
  5. heapify list is [2, 6, 9, 16, 48, 10, 18, 25, 24, 89]
  6. pushed heap is [2, 6, 9, 16, 48, 10, 18, 25, 24, 89, 105]
  7. popped heap is [6, 16, 9, 24, 48, 10, 18, 25, 105, 89]
  8. heappushpop [9, 16, 10, 24, 48, 130, 18, 25, 105, 89]
  9. heapreplace [2, 16, 10, 24, 48, 130, 18, 25, 105, 89]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

希望能对你有所帮助!

 

 

 

 

转载于:https://www.cnblogs.com/audilenovo/p/8876662.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/码创造者/article/detail/1020095
推荐阅读
相关标签
  

闽ICP备14008679号