In Python, heapq.heapify doesn't take cmp or key functions as arguments like sorted does

前端 未结 5 762
离开以前
离开以前 2020-12-10 10:04

I\'m using python2.6. Is it available in higher version of python?
Else is there any other way I can maintain priority queues for list of objects of non-trivial classes?

5条回答
  •  攒了一身酷
    2020-12-10 10:52

    I don't know if this is better but it is like Raymond Hettinger's solution but the priority is determined from the object.

    Let this be your object and you want to sort by the the x attribute.

    class Item:                                 
        def __init__(self, x):
            self.x = x
    

    Then have a function which applies the pairing

    def create_pairs(items):
         return map(lambda item: (item.x, item), items)
    

    Then apply the function to the lists as input into heapq.merge

    list(heapq.merge(create_pairs([Item(1), Item(3)]), 
                     create_pairs([Item(2), Item(5)])))
    

    Which gave me the following output

    [(1, <__main__.Item instance at 0x2660cb0>),
     (2, <__main__.Item instance at 0x26c2830>),
     (3, <__main__.Item instance at 0x26c27e8>),
     (5, <__main__.Item instance at 0x26c2878>)]
    

提交回复
热议问题