I'm trying to convert a nested list into a Treelib representation.
The desired structure of the tree is such that all elements within a list that are not of the type list are at the same hierarchy. A sub-list in the nested list is the child of the element (this has to be an element which is not of type list) immediately preceding it. For instance,
lst = [1,['a','b','c','d',['s','t',['ab','cd',['a','b'],'ef'],'u'],'f']]
would translate to the Treelib representation
from treelib import Node, Tree
tree = Tree()
tree.create_node(1, "root") # We can assume that the list will contain a root node
tree.create_node('a', 'a', parent='root')
tree.create_node('b', 'b', parent='root')
tree.create_node('c', 'c', parent='root')
tree.create_node('d', 'd', parent='root')
tree.create_node('s', 's', parent='d')
tree.create_node('t', 't', parent='d')
tree.create_node('ab', 'ab', parent='t')
tree.create_node('cd', 'cd', parent='t')
tree.create_node('a', 'a1', parent='cd')
tree.create_node('b', 'b1', parent='cd')
tree.create_node('ef', 'ef', parent='t')
tree.create_node('u', 'u', parent='d')
tree.create_node('f', 'f', parent='root')
tree.show()
Desired output:
1
├── a
├── b
├── c
├── d
│ ├── s
│ ├── t
│ │ ├── ab
│ │ ├── cd
│ │ │ ├── a
│ │ │ └── b
│ │ └── ef
│ └── u
└── f
I would guess that this needs some sort of recursive logic to parse the tree and identify the entire hierarchical structure, but I'm not able to come up with the logic for this. How would I write code to generate the Treelib nodes for an arbitrary nested list (which I have manually written here)? Any help would be appreciated.
Edit: A complication here is that entire chunks of the tree can repeat. For instance,
lst = [1,['a','b','c','d',['s','t',['ab','cd',['a','b'],'ef'],'u'],'f','t',['ab','cd',['a','b'],'ef']]]
should translate to the Treelib representation
tree = Tree()
tree.create_node(1, "root") # We can assume that the list will contain a root node
tree.create_node('a', 'a', parent='root')
tree.create_node('b', 'b', parent='root')
tree.create_node('c', 'c', parent='root')
tree.create_node('d', 'd', parent='root')
tree.create_node('s', 's', parent='d')
tree.create_node('t', 't', parent='d')
tree.create_node('ab', 'ab', parent='t')
tree.create_node('cd', 'cd', parent='t')
tree.create_node('a', 'a1', parent='cd')
tree.create_node('b', 'b1', parent='cd')
tree.create_node('ef', 'ef', parent='t')
tree.create_node('u', 'u', parent='d')
tree.create_node('f', 'f', parent='root')
tree.create_node('t', 't1', parent='root')
tree.create_node('ab', 'ab1', parent='t1')
tree.create_node('cd', 'cd1', parent='t1')
tree.create_node('a', 'a2', parent='cd1')
tree.create_node('b', 'b2', parent='cd1')
tree.create_node('ef', 'ef1', parent='t1')
tree.show()
Desired output:
1
├── a
├── b
├── c
├── d
│ ├── s
│ ├── t
│ │ ├── ab
│ │ ├── cd
│ │ │ ├── a
│ │ │ └── b
│ │ └── ef
│ └── u
├── f
└── t
├── ab
├── cd
│ ├── a
│ └── b
└── ef
Thanks!