Turning a flat file into a hierarchical structure

Simon B. sbrunning at bigfoot.com
Tue Dec 5 12:09:53 EST 2000


In article <90j5km$9sv$1 at nnrp1.deja.com>,
  Simon B. <sbrunning at bigfoot.com> wrote:

Sod's law, isn't it - you spend hours trying to puzzle something out,
then withing minutes of posting, the answer comes to you. The working
code (along with slightly more complex test data) looks like this:

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

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

for level, text in testdata:
    if level == lastlevel:
        appendlist.append((level, text, []))
    elif level > lastlevel:
        parentlist.append(appendlist)
        appendlist = appendlist[-1][-1]
        appendlist.append((level, text, []))
    if level < lastlevel:
        while level < appendlist[-1][0]:
            appendlist = parentlist.pop(-1)
        appendlist.append((level, text, []))
    lastlevel = level

print mylist

It goes without saying, though - any pointers from the gurus gratefully
accepted!

--
Simon Brunning
What is a wedding? Webster's Dictionary defines a wedding as 'The
process of removing weeds from one's garden.' - Homer Simpson (giving a
lecture on marriage)


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



More information about the Python-list mailing list