python: how to convert list of lists into a single nested list
Posted
by Bhuski
on Stack Overflow
See other posts from Stack Overflow
or by Bhuski
Published on 2010-05-06T17:53:54Z
Indexed on
2010/05/06
17:58 UTC
Read the original article
Hit count: 412
I have a python list of lists as shown below:
mylist=[ [['orphan1', ['some value1']]],
[['parent1', ['child1', ['child', ['some value2']]]]],
[['parent1', ['child2', ['child', ['some value3']]]]] ]
I need to convert the above list to some thing like this:
result=[ ['orphan1', ['some value1']],
['parent1', ['child1', ['child', ['some value2']]], ['child2', ['child', ['some value3']]]] ]
Kindly help me approach this problem. I have given only simple list. In actual scenario here, in my list, even grand parents/grand childs are there.
How much ever deep the input nested list is, I need to convert it to a single nested list, with common list elements (parents and grand parents) appearing only once. (but the next to innermost list element('child' in above example) should appear as many times it occurs in the input list.
I have been trying to do this last two days, but did not end up with working solution :(.
I need to use the output in django template filter: unordered_list so that the resultant nested list appears as a nested unordered list in my html page ..
© Stack Overflow or respective owner