美文网首页
Python 实践

Python 实践

作者: Yves_lau | 来源:发表于2015-06-12 16:18 被阅读25次

heapq

heapq 提供了基于正规链表的堆实现。最小的值总是保持在 0 点。这在希望循环访问最小元素但是不想执行完整堆排序的时候非常有用:

>>> from heapq import heapify, heappop, heappush
>>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
>>> heapify(data)                      # rearrange the list into heap order
>>> heappush(data, -5)                 # add a new entry
>>> [heappop(data) for i in range(3)]  # fetch the three smallest entries
[-5, 0, 1]

相关文章

网友评论

      本文标题:Python 实践

      本文链接:https://www.haomeiwen.com/subject/scbjqttx.html