How i can sort multidimensional list to two-dimensional list?
Multidimensional input: [8, [6, 7, [-1], [4, [[10]]], 2], 1]
Desired two-dimension
Somebody recently posted a similar question which, by the time I composed my answer, was closed as a duplicate. So I figured I'd add my answer here.
def extract_entries(nested_list, new_list=[]):
# Add the list of all of the items in that are NOT lists themselves.
new_list.append( [ e for e in nested_list if type(e) != list ] )
# Look at entries in that ARE lists themselves.
for entry in nested_list:
if type(entry) == list:
extract_entries(entry, new_list)
return new_list
Testing:
M = [8, [6, 7, [-1], [4, [[10]]], 2], 1]
print(extract_entries(M))
# Returns: [[8, 1], [6, 7, 2], [-1], [4], [], [10]]