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

前端 未结 5 775
离开以前
离开以前 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:40

    Just write an appropriate __lt__ method for the objects in the list so they sort correctly:

    class FirstList(list):
        def __lt__(self, other):
            return self[0] < other[0]
    
    lst = [ ['a', 3], ['b', 1] ]
    
    lst = [FirstList(item) for item in lst]
    

    Only __lt__ is needed by Python for sorting, though it's a good idea to define all of the comparisons or use functools.total_ordering.

    You can see that it is working by using two items with the same first value and different second values. The two objects will swap places when you heapify no matter what the second values are because lst[0] < lst[1] will always be False. If you need the heapify to be stable, you need a more complex comparison.

提交回复
热议问题