Turning a flat file into a hierarchical structure

Simon B. sbrunning at bigfoot.com
Tue Dec 5 11:37:43 EST 2000


I have a tuple which contains a representation of a heirarcical
structure, looking something like this:

testdata = ((1, 'egg '), (2, 'bacon'), (2, 'sausage'), (3, 'spam'),
(4, 'tomato'), (2, 'beans'))

(In real world, this tuple is populated from a text file)

I want to turn this into a tree structure, looking something like this:

[(1, 'egg ', [(2, 'bacon', []), (2, 'sausage', [(3, 'spam',
[(4, 'tomato', [])])]), (2, 'beans')])]

I'm think that I'm nearly there, but I'm stuck on how to deal with
climbing up the tree, that is to say, dealing with the transition from
a lower to a higher level. My existing code looks like this:

mylist = []
appendlist = mylist
lastlevel = testdata[0][0]

for level, text in testdata:
    if level == lastlevel:
        appendlist.append((level, text, []))
    elif level > lastlevel:
        appendlist = appendlist[-1][-1]
        appendlist.append((level, text, []))
    if level < lastlevel:
        break # What here?
    lastlevel = level

print mylist

Can anyone help me out?

--
Simon Brunning
The sooner you fall behind, the more time you'll have to catch up. -
Steven Wright


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list