python 中的 heapq 模块可以使用哪些类型的堆元素?

What types of heap elements can be used with heapq module in python?

在文档中,它提到它可以是元组。但它可以是列表吗?如果是,那么优先级是否默认由列表的第一个元素决定?因为在Priority Queue Implementation Notes里documentation,他们有用list来说明吗?

Python 允许您 heapify 任何 Python iterable (列表、元组、字符串等) .

所以,是的,列表和元组可以用作元素而不仅仅是整数 但前提是可迭代对象可以支持其元素之间 lexicographical 顺序[=29]的有效比较=].让我们动手吧。

>>> a = (0, "hello")
>>> b = (1, "word")
>>> array = [a, b]
>>> heapq.heapify(array)
>>> heapq.heappop(array)
(0, 'hello')

一切看起来都不错,我们能够堆化一个元组列表,其中每个元组包含一个 int 和一个字符串。再看一个例子:

>>> a = (0, "hello")
>>> b = ("word", 1)
>>> array = [a, b]
>>> heapq.heapify(array)
>>> heapq.heapify(array)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'

如您所见,python 解释器开始抱怨,因为它无法比较 int 和 str。

出于同样的原因,您将无法堆化一个字典列表 (List[Dict]),但您可以堆化一个 int 列表 (List[int]),甚至堆化一个列表整数列表 (List[List[int]])。证明如下:

>>> a = {0:'hello', 1:'world'}
>>> b = {0:'hola', 1:'mundo'}
>>> array = [a, b]
>>> heapq.heapify(array)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'
>>>
>>>
>>> a = [1,2,3,4]
>>> b = [5,6,7]
>>> array = [a, b]
>>> heapq.heapify(array)
>>> heapq.heappop(array)
[1, 2, 3, 4]