python - 类型错误 : unorderable types: dict() < dict() in heapq

标签 python python-3.x heap

我正在移植适用于 python2 的代码。在移植它时出现错误 unorderable types: dict() < dict()在下面的行

heapq.heappush(colors, color) #this throws error
return heapq.nsmallest(count, colors, key=lambda k: k['shade'])

这些是类型:

`colors` is a <class 'list'>
`color` is a <class 'dict'>

如何在 python3 中实现此功能?

最佳答案

您根本不需要在这里调用 heapppush,因为 nsmallest 已经处理了堆排序。它在内部创建一个堆并将项目推送到上面。 nsmallest 本身不需要字典可排序,因为您指定了 key 参数。

只需用 colors.append(color) 替换 heappush 调用即可。

请注意,虽然您的代码可以在 Python 2 中运行,但它所做的只是在调用 nsmallest 之前以任意顺序重新排列 colors 列表。

关于python - 类型错误 : unorderable types: dict() < dict() in heapq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34005451/

相关文章:

python - 获取卷积算法失败。这可能是因为 cuDNN 初始化失败,

python - 我如何在 django 中的包含标记中传递请求对象

python - heapq.nlargest 的时间复杂度是多少?

c++ - C++ 中的嵌套字典/数组

python - Django-Celery 数据库访问

python - 如何在 yield 中扩展元组?

python - 如何与micro建立串口通信:bit using PySerial?

python - 有没有办法使用 Python-C API 调整 python 列表的大小?

java - 从二进制最大堆中删除根节点的算法

java - 插入和删除最大堆java