【发布时间】:2021-07-11 17:01:09
【问题描述】:
我正在尝试将嵌套列表转换为 Treelib 表示形式。
所需的树结构是列表中所有不属于list 类型的元素都处于相同的层次结构中。嵌套列表中的子列表是紧接在其前面的元素的子元素(这必须是不属于list 类型的元素)。例如,
lst = [1,['a','b','c','d',['s','t',['ab','cd',['a','b'],'ef'],'u'],'f']]
将转换为 Treelib 表示
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()
期望的输出:
1
├── a
├── b
├── c
├── d
│ ├── s
│ ├── t
│ │ ├── ab
│ │ ├── cd
│ │ │ ├── a
│ │ │ └── b
│ │ └── ef
│ └── u
└── f
我猜这需要某种递归逻辑来解析树并识别整个层次结构,但我无法为此提出逻辑。我将如何编写代码来为任意嵌套列表(我在这里手动编写)生成 Treelib 节点?任何帮助将不胜感激。
编辑:这里的复杂性是树的整个块可以重复。例如,
lst = [1,['a','b','c','d',['s','t',['ab','cd',['a','b'],'ef'],'u'],'f','t',['ab','cd',['a','b'],'ef']]]
应该转换为 Treelib 表示
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()
期望的输出:
1
├── a
├── b
├── c
├── d
│ ├── s
│ ├── t
│ │ ├── ab
│ │ ├── cd
│ │ │ ├── a
│ │ │ └── b
│ │ └── ef
│ └── u
├── f
└── t
├── ab
├── cd
│ ├── a
│ └── b
└── ef
谢谢!
【问题讨论】: