Python - How to sort multidimensional list to two-dimensional list?

后端 未结 6 498
遥遥无期
遥遥无期 2021-01-18 18:39

How i can sort multidimensional list to two-dimensional list?

Multidimensional input: [8, [6, 7, [-1], [4, [[10]]], 2], 1]

Desired two-dimension

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 19:12

    My option with recursion and without any dependencies:

    lst = [8, [6, 7, [-1], [4, [[10]]], 2], 1]
    
    def flat_group(lst, deep = 0, res = None):
      if res == None: res = []
      for item in lst:
        if len(res) <= deep: res.append([])
        if not type(item) == list:
          res[deep].append((item))
        else:
          flat_group(item, deep + 1, res)
      return res
    
    
    print(flat_group(lst))
    #=> [[8, 1], [6, 7, 2], [-1, 4], [], [10]]
    


    To show How it works, I split the method in two:

    def flat(lst, deep = 0, res = []):
      for item in lst:
        if not type(item) == list:
          res.append((deep, item))
        else:
          flat(item, deep + 1, res)
      return res
    
    def group(lst):
      flatten = flat(lst)
      max_n = max(flatten)[0]
      res = [[] for _ in range(0,max_n+1)]
      for deep, item in flatten:
        res[deep].append(item)
      return res
    
    print(group(lst))
    #=> [[8, 1], [6, 7, 2], [-1, 4], [], [10]]
    

    flat(lst) is a recursive method that builds a flat list of tuples where each tuple contains the value and the deep inside the original list. So the call flat(lst) returns:

    # [(0, 8), (1, 6), (1, 7), (2, -1), (2, 4), (4, 10), (1, 2), (0, 1)]
    

    Then group(lst) builds a list of n+1 empty sub-list, where n is the maximum depth, it iterates over the result of flat(lst) and append each element by index to the proper sub-list.

    The flat_group(lst) does almost the same.

提交回复
热议问题