Я некоторое время боролся с этим, надеясь, что кто-нибудь может мне помочь. Я так близко, но когда я получаю 3 поколения, это не создает дополнительный список, как в списке. Мне нужно, чтобы код был максимально легким, поэтому стараюсь избегать сторонних модулей в конечном продукте. Очевидно, что сейчас я использую PrettyPrint, чтобы упростить проверку при печати.
Данные
Root
Child 1
Child 2
Grandchild 1
Grandchild 2
Grandchild's Child 1
Grandchild's Child 2
Child 3
Child 4
3 Indents in Child 1
3 Indents in Child 2
Root2
Child 1
Grandchild 1
Grandchild's Child 1
Grandchild's Child 2
Child 2
Grandchild 2
Мой код
for line in data_output:
clean_line = line.lstrip().replace('"', '').replace("'","")
current_indent = (len(line) - len(clean_line)) / 4
try:
previous_indent = (len(data_output[line_incrementer - 1]) - len(data_output[line_incrementer - 1].lstrip())) / 4
next_indent = (len(data_output[line_incrementer + 1]) - len(data_output[line_incrementer + 1].lstrip())) / 4
# DEBUG
# print("prev [" + str(line_incrementer) + "]" + str(previous_indents) + " - next [" + str(line_incrementer) + "]" + str(next_indents) + " - line [" + str(line_incrementer) + "]" + str(line_indents))
except:
previous_indent = None
next_indent = None
if current_indent == 0:
parent_list = [clean_line]
data_dump.append(parent_list)
elif current_indent > 0 and current_indent != indentation_level:
active_list = [clean_line]
parent_list.append(active_list)
elif current_indent > 0 and current_indent == indentation_level:
active_list.append(clean_line)
parent_list = active_list
indentation_level = current_indent
line_incrementer += 1
pprint.pprint(data_dump)```
Ожидаемый результат
[
['Root',
[
'Child 1',
'Child 2',
[
'Grandchild 1',
'Grandchild 2'
],
'Child 3',
'Child 4',
[
'3 Indents in Child 1',
'3 Indents in Child 2'
]
]
],
['Root2',
[
'Child 1',
[
'Grandchild 1',
[
'Grandchilds Child 1',
'Grandchilds Child 2'
]
],
'Child 2',
[
'Grandchild'
]
]
]
]