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

后端 未结 6 542
遥遥无期
遥遥无期 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

    The recursive approach taken by the other answers comes with the recursion limit imposed by Python and the overhead of two passes. A more efficient one-pass iterative approach is to implement breadth-first search using a queue of tuples of lists and associated depths:

    from collections import deque
    def flatten(lst):
        output = []
        q = deque([(lst, 0)])
        while q:
            l, depth = q.popleft()
            for i in l:
                if isinstance(i, list):
                    q.append((i, depth + 1))
                else:
                    while depth >= len(output):
                        output.append([])
                    output[-1].append(i)
        return output
    

    so that:

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

    returns:

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

提交回复
热议问题