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