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

后端 未结 6 495
遥遥无期
遥遥无期 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 18:57

    You could perhaps use a defaultdict here to measure the depth of each element, along with recursion:

    from collections import defaultdict
    L = [8, [6, 7, [-1], [4, [[10]]], 2], 1]
    res = defaultdict(list)
    def myfunc(L, depth):
        for i in L:
            if isinstance(i, list):
                myfunc(i, depth+1)
            else:
                res[depth].append(i)
    
    myfunc(L, 0)
    

    The defaultdict will then look like this:

    defaultdict(, {0: [8, 1], 1: [6, 7, 2], 2: [-1, 4], 4: [10]})
    

    You'll then need to translate the defaultdict back to what you want. Note that the default dict will not contain an empty list because it can't detect it (ie: [[10]] and [10] are both lists), but what it will have is a gap in the range (notice how the depth 3 is missing in the defaultdict).

    final = []
    for i in range(max(res)+1):
        if i not in res:
            final.append([])
        else:
            final.append(res[i])
    
    print(final)
    

    Very messy, I'm sure improvements could be made.

提交回复
热议问题