How to make heapq evaluate the heap off of a specific attribute?

后端 未结 7 715
野的像风
野的像风 2020-11-30 22:07

I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq,

相关标签:
7条回答
  • 2020-11-30 23:03

    Unfortunately, you can't, although this is an often requested feature.

    One option would be to insert (key, value) tuples into the heap. However, that won't work if the values throw an exception when compared (they will be compared in the case of a tie between keys).

    A second option would be to define a __lt__ (less-than) method in the class that will use the appropriate attribute to compare the elements for sorting. However, that might not be possible if the objects were created by another package or if you need them to compare differently elsewhere in the program.

    A third option would be to use the sortedlist class from the blist module (disclaimer: I'm the author). The constructor for sortedlist takes a key parameter that lets you specify a function to return the sort key of an element, similar to the key parameter of list.sort and sorted.

    0 讨论(0)
提交回复
热议问题