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

后端 未结 7 748
野的像风
野的像风 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 22:53

    According to the Official Document, a solution to this is to store entries as tuples (please take a look at Section 8.4.1 and 8.4.2).

    For example, your object is something like this in tuple's format (key, value_1, value_2)

    When you put the objects (i.e. tuples) into heap, it will take the first attribute in the object (in this case is key) to compare. If a tie happens, the heap will use the next attribute (i.e. value_1) and so on.

    For example:

    import heapq
    
    heap = []
    heapq.heappush(heap, (0,'one', 1))
    heapq.heappush(heap, (1,'two', 11))
    heapq.heappush(heap, (1, 'two', 2))
    heapq.heappush(heap, (1, 'one', 3))
    heapq.heappush(heap, (1,'two', 3))
    heapq.heappush(heap, (1,'one', 4))
    heapq.heappush(heap, (1,'two', 5))
    heapq.heappush(heap, (1,'one', 1))
    
    show_tree(heap)
    

    Output:

                                          (0, 'one', 1)                                       
                    (1, 'one', 1)                                (1, 'one', 4)                
        (1, 'one', 3)         (1, 'two', 3)         (1, 'two', 2)         (1, 'two', 5)     
    (1, 'two', 11)
    

    About pretty print a heap in python (updated the link): show_tree()

提交回复
热议问题