在现实生活中,您将使用heapq Python模块做什么? [英] What would you use the heapq Python module for in real life?

查看:170
本文介绍了在现实生活中,您将使用heapq Python模块做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读Guido的将一百万使用Python在2MB RAM中使用32位整数,我发现了 heapq 模块,但是这个概念对我来说很抽象。

After reading Guido's Sorting a million 32-bit integers in 2MB of RAM using Python, I discovered the heapq module, but the concept is pretty abstract to me.

一个原因是我不完全了解堆的概念,但我确实了解Guido的用法。

One reason is that I don't understand the concept of a heap completely, but I do understand how Guido used it.

现在,除了他的疯狂例子之外,您将使用 heapq 模块做什么?

Now, beside his kinda crazy example, what would you use the heapq module for?

必须始终与排序有关或最小值?它只是您使用的东西,因为它比其他方法更快吗?还是您可以做一些您无法做到的优雅的事情?

Must it always be related to sorting or minimum value? Is it only something you use because it's faster than other approaches? Or can you do really elegant things that you can't do without?

推荐答案

heapq模块通常用于实现优先级队列

您会看到事件调度程序中的优先级队列,这些优先级队列不断添加新事件,并且需要使用堆来有效地定位下一个预定的事件。一些示例包括:

You see priority queues in event schedulers that are constantly adding new events and need to use a heap to efficiently locate the next scheduled event. Some examples include:

  • Python's own sched module: http://hg.python.org/cpython/file/2.7/Lib/sched.py#l106
  • The Tornado web server: https://github.com/facebook/tornado/blob/master/tornado/ioloop.py#L260
  • Twisted internet servers: http://twistedmatrix.com/trac/browser/trunk/twisted/internet/base.py#L712

heapq文档包括优先队列实施说明,用于解决常见的用例。

The heapq docs include priority queue implementation notes which address the common use cases.

此外,堆非常适合实现部分排序。例如, heapq.nsmallest heapq.nlargest 可以提高内存使用效率并比进行完整排序后再进行切片的次数少得多:

In addition, heaps are great for implementing partial sorts. For example, heapq.nsmallest and heapq.nlargest can be much more memory efficient and do many fewer comparisons than a full sort followed by a slice:

>>> from heapq import nlargest
>>> from random import random
>>> nlargest(5, (random() for i in xrange(1000000)))
[0.9999995650034837, 0.9999985756262746, 0.9999971934450994, 0.9999960394998497, 0.9999949126363714]

这篇关于在现实生活中,您将使用heapq Python模块做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆