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


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

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

Desired two-dimensional output: [[8, 1], [6, 7, 2], [-1, 4], [], [10]]

all same depth list items need to be in same list.


Answer

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]]