is there an easy way to parse a nested list ?
Aaron Brady
castironpi at gmail.com
Mon Mar 16 04:38:49 EDT 2009
On Mar 15, 6:44 pm, Stef Mientki <stef.mien... at gmail.com> wrote:
> hello,
>
> I need to parse a nested list, given as a string, like this
>
> line = " A [ B [ C+2 ] + 3 ] "
>
> ( I probably can do it with find, but I guess that's not the most
> elegant way, besides recusrion is not my strongest point)
>
> which should be parsed so I get an list from inner to outer side (don't
> know if these are the correct words),
> but I should like to have a list or tuple for tis case:
>
> parsed = [ C+2, B[C+2]+3, A [ B [ C+2 ] + 3 ] ]
> or (last term is not needed, as well as the constants aren't)
> parsed = [ C, B[C+2] ]
>
> this all, to improve the improved error / exception message even more ;-)
>
> thanks,
> Stef
Hi Stef,
This looks like what you want:
def parse_list( s, start= 0 ):
x= []
i= start
while i< len( s ):
c= s[ i ]
if c== '[':
y, i= parse_list( s, i+ 1 )
x= x+ y
if c== ']':
return x+ [ s[start: i ] ], i
i+= 1
return x+ [ s ]
line = " A [ B [ C+2 ] + 3 ] "
print( parse_list( line ) )
#[' C+2 ', ' B [ C+2 ] + 3 ', ' A [ B [ C+2 ] + 3 ] ']
line = " A [ B [ C+2 ] [ D+2 ] + 3 ] "
print( parse_list( line ) )
#[' C+2 ', ' D+2 ', ' B [ C+2 ] [ D+2 ] + 3 ', ' A [ B [ C+2 ] [ D
+2 ] + 3 ] ']
...So long as you don't have any brackets inside strings or what not.
It just admits two special characters, '[' and ']'.
More information about the Python-list
mailing list