>> heappush(heap,(0,{"k-6ren">
gpt4 book ai didi

python - 如果项目不可比较,heapq 无法处理具有相同优先级的元组

转载 作者:行者123 更新时间:2023-12-01 00:45:44 30 4
gpt4 key购买 nike

>>> from heapq import heappush
>>> heap = []
>>> heappush(heap,(0,{"k":0}))
>>> heappush(heap,(0,{"k":1}))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'dict' and 'dict'

official heapq document for python2 中提到了这一点 and python3该文档建议使用 heapq DIY 实现来缓解此问题。

为什么会发生这种情况?鉴于 heapq 是一个非常旧的库,这种冲突没有得到解决的根本原因是什么?是否有性能/其他问题?为什么我们不能只提供像 keep_old, keep_any 这样的参数作为该库的一项功能?

最佳答案

摘自 Priority Queue Implementation Notes 上的 heapq 文档部分:

A solution to the first two challenges is to store entries as 3-element list including the priority, an entry count, and the task. The entry count serves as a tie-breaker so that two tasks with the same priority are returned in the order they were added.

对此的简单解释:

from heapq import heappush
ecount = 0
heap = []

for priority, task in (
(0, {"k":0}),
(0, {"k":0}),
):
heappush(heap, (priority, ecount, task))
ecount += 1

结果:

>>> heap
[(0, 0, {'k': 0}), (0, 1, {'k': 0})]

(您也可以使用 enumerate() 来执行此操作。)

<小时/>

向事物注入(inject)一些观点:

Why is this happening? What is the underlying reason that such conflict is not resolved, giving that heapq is a really old library?

不太确定,但事实是你无法在逻辑上比较两个dict小于/大于。

独立于 heapq,比较 (0,{"k":0}) > (0,{"k":1}) 将(理所当然)引发TypeErrorheapq的一个重点是操作应该是确定性:决胜局不应该是随机的,由您根据具体情况决定如何处理。

关于python - 如果项目不可比较,heapq 无法处理具有相同优先级的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56998340/

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