gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:15 31 4
gpt4 key购买 nike

在文档中,它提到它可能是元组。但它可以是列表吗?如果是,那么优先级默认是由列表的第一个元素决定的吗?因为在优先级队列实现笔记中documentation ,他们有用list来说明吗?

最佳答案

Python 允许您堆化任何 Python 可迭代(列表、元组、字符串等)。

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

>>> 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])甚至列表列表int(列表[列表[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]

关于python - python 中的 heapq 模块可以使用哪些类型的堆元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59516028/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com