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

后端 未结 6 537
遥遥无期
遥遥无期 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条回答
  •  渐次进展
    2021-01-18 19:05

    The idea is basically the same that the one in @TerryA answer, but using setdefault and checking at the end of the for loop if something of the depth was added:

    lst = [8, [6, 7, [-1], [4, [[10]]], 2], 1]
    
    
    def depths(l):
        def flatten(l, start=0, depth={}):
    
            for e in l:
                if isinstance(e, list):
                    flatten(e, start=start + 1, depth=depth)
                else:
                    depth.setdefault(start, []).append(e)
             if start not in depth:
                depth[start] = []
    
        d = {}
        flatten(l, depth=d)
    
        return [d[i] for i in range(max(d) + 1)]
    
    
    result = depths(lst)
    print(result)
    

    Output

    [[8, 1], [6, 7, 2], [-1, 4], [], [10]]
    

提交回复
热议问题