TypeError:unorderable类型:dict()< heapq中的dict()

时间:2015-11-30 18:27:52

标签: 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中完成这项工作?

2 个答案:

答案 0 :(得分:2)

您根本不需要在此处调用<div contenteditable="true"> <p>This is an editable paragraph.</p> <figure> <img src="http://www.keenthemes.com/preview/metronic/theme/assets/global/plugins/jcrop/demos/demo_files/image1.jpg"> </figure> <p>This is an editable paragraph.</p> </div> ,因为heapppush已经处理了堆排序。它在内部创建一个堆并在其上推送项目。 nsmallest本身不需要可以订购,因为您指定了nsmallest参数。

只需用key替换heappush通话。

请注意,尽管您的代码在Python 2中有效,但它只是在调用colors.append(color)之前以任意顺序重新排列colors列表。

答案 1 :(得分:1)

如果您希望可以订购字典,则不能使用常规类型。但是,您可以使用(不可变的)frozendict。见https://github.com/slezica/python-frozendict

只将frozendict放入您的列表中,所有内容都应正常运行。

相关问题