Вы можете создать словарь из сплющенных значений, а затем использовать рекурсию:
import re
d = ['.', ['A', 'B', 'C', 'D', 'E', 'F']], ['A', ['G', 'H']], ['A\\G', []], ['A\\H', ['K', 'L']], ['A\\G\\K', []], ['A\\G\\L', []], ['B', ['I', 'J']], ['B\\I', []], ['B\\J', []], ['C', []], ['D', []], ['E', []], ['F', ['M']], ['F\\M', []]
new_d = {re.findall('.$', a)[0]:b for a, b in d}
def _tree(_start):
if not new_d[_start]:
return _start
_c = [_tree(i) for i in new_d[_start]]
return [_start, *(_c if any(not isinstance(i, str) for i in _c) else [_c])]
print(_tree('.'))
Вывод:
['.', ['A', 'G', ['H', ['K', 'L']]], ['B', ['I', 'J']], 'C', 'D', 'E', ['F', ['M']]]
Редактировать: версия Python2:
import re
d = ['.', ['A', 'B', 'C', 'D', 'E', 'F']], ['A', ['G', 'H']], ['A\\G', []], ['A\\H', ['K', 'L']], ['A\\G\\K', []], ['A\\G\\L', []], ['B', ['I', 'J']], ['B\\I', []], ['B\\J', []], ['C', []], ['D', []], ['E', []], ['F', ['M']], ['F\\M', []]
new_d = {re.findall('.$', a)[0]:b for a, b in d}
def _tree(_start):
if not new_d[_start]:
return _start
_c = [_tree(i) for i in new_d[_start]]
return [_start]+(_c if any(not isinstance(i, str) for i in _c) else [_c])
print(_tree('.'))