【发布时间】:2020-02-03 12:31:05
【问题描述】:
我有一个动态树结构,它表示为列表列表 - 这是一个这样的示例,用空格布局以说明结构:
[['第一的', [0, 'list1'], [1, 'list2'], [2, 'list3']], ['第二', ['second_subda', [0, 'tup1'], [1, 'tup2']], ['second_subdb', [0, 'tup3'], [1, 'tup4']]], ['第三', ['third_subda', [0, 'a'], [1, 'b'], [2, 'c'], [3, ['d', [0, 'e'], [1, 'f'], [2, ['G', [0, 1], [1, 2], [2, 3]]]]]]]]我想从中提取所有叶节点以及到达它们所需的路径:
例如从上面的结构,我想返回:
[ ('list1', ['first', 0 ]) , ('list2', ['first', 1 ]) , ('list3', ['first', 2 ]) , ('tup1', ['second', 'second_subda', 0]) , ('tup2',['second','second_subda',1]), ('tup3', ['second', 'second_subdb', 0]) , ( 'tup4' , ['second', 'second_subdb', 1 ] ) , ('a', ['third', 'third_subda', 0]) , ( 'b' , ['third', 'third_subda', 1 ] ) , ('c', ['third', 'third_subda', 2]) , ('e', ['third', 'third_subda', 3, 'd', 0]) , ('f',['third','third_subda',3,'d',1]), (1,['第三','third_subda',3,'d',2,'g',0]), ( 2 , ['third', 'third_subda', 3 , 'd', 2 , 'g' , 1 ]) , ( 3 , ['第三', 'third_subda', 3 , 'd', 2 , 'g' , 2 ])]即对于每个“叶子”,我想提取一个包含所有叶子值的元组,以及描述到达该叶子项的唯一路径的所有初始列表条目的列表。我应该留下这些元组的列表,其中列表中的项目数对应于树中叶节点的数量。
我尝试在 networkx 之类的模块中构建此树,但对于我的用例而言,额外模块的开销太大了。我只想在可能的情况下坚持使用香草 python 代码。
【问题讨论】: