How i can sort multidimensional list to two-dimensional list?
Multidimensional input: [8, [6, 7, [-1], [4, [[10]]], 2], 1]
Desired two-dimension
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.