How to get such nested lists?

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) 
  • Result
    nestedList1: [[['bb1'], [['aa3'], 'aa1', 'aa2'], 'aa', 'bb'], 'root']
    nestedList2: [[['cc1'], [[['bb4'], 'bb2', 'bb3'], 'bb1'], [['aa3'], 'aa1', 'aa2'], 'aa', 'bb', 'cc'], 'root']

All I want is the results below.

  • Result
    nestedList1: [[[['aa3'], 'aa1', 'aa2'], 'aa', ['bb1'], 'bb'], 'root']
    nestedList2: [[[['aa3'], 'aa1', 'aa2'], 'aa', [[['bb4'], 'bb2', 'bb3'], 'bb1'], 'bb', ['cc1'], 'cc'], 'root']

How to get such a nested list? I need a nested list to be mailed.

+5
source share
2 answers

Basically what you need to do to reorder the list: whenever the nth element is a label and the element n+1 -th is a sublayer, replace two. You can do this in place in a few lines:

 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] 

For an in-place solution, you can simply create a deep copy of the list and then use it in the copy.

+2
source

I may be out of line here or miss the point completely, but I will risk asserting that I think it will be easier if you put each branch completely in brackets. those. write each branch as distinctive [root, [branch1], [branch2], ...]

 nestedList1 = ['root', ['aa', ['aa1', ['aa3']], ['aa2']], ['bb', ['bb1']]] nestedList2 = ['root', ['aa', ['aa1', ['aa3']], ['aa2']], ['bb', ['bb1', ['bb2', ['bb4']], ['bb3']]], ['cc', ['cc1']]] 

Then you can just recursively reorder so that each branch leaves - 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 

Results of modified nested lists:

 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'] 

Is that what you were after?

Finding which branch is deeper for a good build is another topic.

0
source

All Articles