git.net

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

iterate through an irregular nested list in Python


On Fri, Mar 6, 2020 at 6:55 AM Pieter van Oostrum <pieter-l at vanoostrum.org> wrote:

> sinndhhu at gmail.com writes:
>
> > Hi All,
> > I am new to python.
> > I have a irregular nested lists in a list.
> > Please help me to iterate through each element.
> >
> > Thanks much in advance.
> >
> > Sample Ex
> >
> > aList = [[2,'jkj'],[],[],['kite',88,'ooo','pop','push','pull'],['hello']]
> >
> > expected output:
> > 2,jkj,,,kite,88,ooo,pop,push,pull,hello
> >
>
> Use a recursive iterator/generator:
> It becomes a bit peculiar because you want special treatment for empty
> lists inside,
> but otherwise it is quite standard Python:
>
> aList = [[2,'jkj'],[],[],['kite',88,'ooo','pop','push','pull'],['hello']]
>
> def reclist(aList):
>     for item in aList:
>         if isinstance(item, list):
>             if item == []:
>                 yield ''
>             else:
>                 yield from reclist(item)
>         else:
>             yield item
>
> for i in reclist(aList):
>     print(i, end=',')
>
> This gives you an extra comma at the end, unfortunately.
> But it is the pattern for other types of processing.
>
> Or use it like this:
>
> print (','.join(str(i) for i in reclist(aList)))
>

If your lists are nested to inconsistent depth, and you're on a modern version of Python (3.3 and up), recursion with yield from (as above) is the way to go.

If your lists are nested to a consistent depth (as your example seems to suggest), you can just:

for sublist in aList:
    for element in sublist:
        yield element

If you need inconsistent depth and you're on an old version of python, yield from is unavailable. In that case, it's best to write it out recursively (even though that won't work really), and modify that to be nonrecursive using an explicit stack or stacks. There's an example of this at:
http://stromberg.dnsalias.org/svn/treap/trunk/m4_treap.m4
See iterator_macro.
Don't let the m4 throw you - it's just a way of deriving pure python and cython from the same file.
You can generate the pure python form the .m4 file with simply: m4 -Dpy=1 < m4_treap.m4 > py_treap.py
...if you install an m4 binary.

HTH.