Merge sorted lists in python

前端 未结 9 1002
花落未央
花落未央 2020-12-19 00:50

I have a bunch of sorted lists of objects, and a comparison function

class Obj :
    def __init__(p) :
        self.points = p
def cmp(a, b) :
    return a.p         


        
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-19 01:14

    One line solution using sorted:

    def magic(*args):
      return sorted(sum(args,[]), key: lambda x: x.points)
    

    IMO this solution is very readable.

    Using heapq module, it could be more efficient, but I have not tested it. You cannot specify cmp/key function in heapq, so you have to implement Obj to be implicitly sorted.

    import heapq
    def magic(*args):
      h = []
      for a in args:
        heapq.heappush(h,a)
      return [i for i in heapq.heappop(h)
    

提交回复
热议问题