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)
[[['bb1'], [['aa3'], 'aa1', 'aa2'], 'aa', 'bb'], 'root']
[[['cc1'], [[['bb4'], 'bb2', 'bb3'], 'bb1'], [['aa3'], 'aa1', 'aa2'], 'aa', 'bb', 'cc'], 'root']
我想要的只是下面的结果。
[[[['aa3'], 'aa1', 'aa2'], 'aa', ['bb1'], 'bb'], 'root']
[[[['aa3'], 'aa1', 'aa2'], 'aa', [[['bb4'], 'bb2', 'bb3'], 'bb1'], 'bb', ['cc1'], 'cc'], 'root']
如何获得这样的嵌套列表? 我想要一个嵌套列表,命令下订单遍历。
答案 0 :(得分:2)
基本上,为了对列表重新排序,您需要做什么:每当n
元素是标签,n+1
元素是子列表时,交换这两个元素。您可以在以下几行就地执行此操作:
def reorder(lst):
for i, (cur, nxt) in enumerate(zip(lst, lst[1:])):
if isinstance(cur, str) and isinstance(nxt, list):
reorder(nxt)
lst[i:i+2] = [nxt, cur]
对于 not-in-place 解决方案,您只需创建列表的深层副本,然后在副本上使用该副本。
答案 1 :(得分:0)
我可能在这里不合适,或者完全忽略了这一点,但是如果你将每个分支完全收集到括号中,我会冒险声称我会更容易。即将每个分支写为独特的[root,[branch1],[branch2],...]
nestedList1 = ['root', ['aa', ['aa1', ['aa3']], ['aa2']], ['bb', ['bb1']]]
nestedList2 = ['root', ['aa', ['aa1', ['aa3']], ['aa2']], ['bb', ['bb1', ['bb2', ['bb4']], ['bb3']]], ['cc', ['cc1']]]
然后你可以递归地改变顺序,使每个分支离开 - 1st,trunk-2nd。
def recursivereverese(l):
if len(l)<=1 or type(l) is not list:
return l
else:
new = []
for k in l[::-1]:
new.append(recursivereverese(k))
return new
修改后的嵌套列表的结果:
In [127]: recursivereverese(nestedList1)
Out[127]: [[['bb1'], 'bb'], [['aa2'], [['aa3'], 'aa1'], 'aa'], 'root']
In [128]: recursivereverese(nestedList2)
Out[128]:
[[['cc1'], 'cc'],
[[['bb3'], [['bb4'], 'bb2'], 'bb1'], 'bb'],
[['aa2'], [['aa3'], 'aa1'], 'aa'],
'root']
这是你追求的吗?
找出更好的绘图分支是一个不同的主题。