Я предлагаю это решение.По крайней мере, это работает с примером, который вы дали.Пожалуйста, задавайте вопросы, если вам нужны какие-либо объяснения кода ниже: комментарии должны направлять вас.
lst_string = ['1,2,3,4', '2,5,6', '3,7,8', '4,9']
# first, transform your list into a nested list
# create an empty list
lst_nested = list()
for seq_string in lst_string:
to_list = list(seq_string) # the first list looks like ["1", ",", "2", ",", "3", ",", "4']
to_list = to_list[0::2] # this removes the "," inputs
to_list = list(map(int, to_list)) # this transforms ["1", "2", "3"] into [1,2,3]
lst_nested.append(to_list)
# define the list of first elements
first_elements = list()
for lst in lst_nested:
first_elements.append(lst[0])
# prepare the output
tab = "...."
def fill_in(seq, idx_tab):
# always displays the first element
output = ""
output += tab * idx_tab
output += str(seq[0])
output += "\n"
for intgr in seq[1:]:
if intgr in first_elements:
# call recursively function fill_in with the corresponding seq
output += fill_in(lst_nested[first_elements.index(intgr)], idx_tab + 1)
else:
output += tab * (idx_tab + 1)
output += str(intgr)
output += "\n"
return output
print(fill_in(lst_nested[0], 0))