Format list of list sub elements keeping structure.

Sayth Renshaw flebber.crue at gmail.com
Mon Jul 23 21:52:19 EDT 2018


I have data which is a list of lists of all the full paths in a json document.

How can I change the format to be usable when selecting elements?

data = [['glossary'],
 ['glossary', 'title'],
 ['glossary', 'GlossDiv'],
 ['glossary', 'GlossDiv', 'title'],
 ['glossary', 'GlossDiv', 'GlossList'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'ID'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'SortAs'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossTerm'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'Acronym'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'Abbrev'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef', 'para'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef', 'GlossSeeAlso'],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef', 'GlossSeeAlso', 0],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossDef', 'GlossSeeAlso', 1],
 ['glossary', 'GlossDiv', 'GlossList', 'GlossEntry', 'GlossSee']]

I am trying to change it to be.

[['glossary'],
 ['glossary']['title'],
 ['glossary']['GlossDiv'],
....]

Currently when I am formatting I am flattening the structure(accidentally).

for item in data:
    for elem in item:
        out = ("[{0}]").format(elem)
    print(out)

Which gives

[glossary]
[title]
[GlossDiv]
[title]
[GlossList]
[GlossEntry]
[ID]
[SortAs]
[GlossTerm]
[Acronym]
[Abbrev]
[GlossDef]
[para]
[GlossSeeAlso]
[0]
[1]
[GlossSee]


Cheers

Sayth


More information about the Python-list mailing list