variable tree structure
- nestedList1 variable
aa3
|
aa1 aa2 bb1
\ / /
aa bb
\ /
root
- nestedList2 variable
bb4
|
aa3 bb2 bb3
| \ /
aa1 aa2 bb1 cc1
\ / / |
aa bb cc
\ | /
root
nestedList1 = ['root', ['aa', ['aa1', ['aa3'], 'aa2'], 'bb', ['bb1']]]
nestedList2 = ['root', ['aa', ['aa1', ['aa3'], 'aa2'], 'bb', ['bb1', ['bb2', ['bb4'], 'bb3']], 'cc', ['cc1']]]
def ConvertTraverse(nlist, depth=0):
convertlist = []
for leaf in nlist:
if isinstance(leaf, list):
tmplist = ConvertTraverse(leaf, depth+1)
convertlist.insert(0, tmplist)
else:
convertlist += [leaf]
return convertlist
print ConvertTraverse(nestedList1)
print ConvertTraverse(nestedList2)
- 结果
nestedList1:[[[['aa3'], 'aa1', 'aa2'], 'aa', ['bb1'], 'bb'], 'root']
nestedList2:[[[['aa3'], 'aa1', 'aa2'], 'aa', [[['bb4'], 'bb2', 'bb3'], 'bb1'], 'bb', ['cc1'], 'cc'], 'root']
如何获取这样的嵌套列表? 我想要一个按后序遍历顺序排序的嵌套列表。
nestedList1 = ['root',['aa',['aa1',['aa3']],['aa2']],['bb',['bb1']]]
,然后可以递归地将第一个项目移动到最后。但是,如果您想要确保进行最深层次的裁剪,则需要进行更多操作。 - Aguy