[Tutor] How can I extract a specific sublist from a nested list?

Emad Nawfal (عماد نوفل) emadnawfal at gmail.com
Wed Mar 11 22:21:07 CET 2009


On Wed, Mar 11, 2009 at 7:47 AM, Andre Engels <andreengels at gmail.com> wrote:

> 2009/3/11 Emad Nawfal (عماد نوفل) <emadnawfal at gmail.com>:
>
> > Now I know that I did not ask the right question. What I meant was: how
> to
> > extract a sublist from a list whose length is unknown. Let's say I have a
> > hundred of these lists and each of these has an NP somewhere, it could be
> > nested in nested list, which is turn nested in another one and so on. The
> > bottom line is that I do not know the index.  To make things more
> concrete,
> > this is a representative list. How can I extract all the sublists
> beginning
> > with "NP" from it?
>
> You'll have to do recursion - that is:
> NPstart(alist) =
>   if alist starts with "NP":
>       alist + NPstart for all sublists of alist
>   else:
>       NPstart for all sublists of alist
>
>
> Turning that into Python we get:
>
> def NPstart(alist):
>   if isinstance(alist, basestring): # It's ugly to do an isinstance
> in Python, but any better method would be fully changing your data
> structure, so I use it for now
>       return []
>   else:
>       if alist[0] == 'NP':
>           return [alist] + [NPstart(sublist) for sublist in alist]
>       else:
>           return [NPstart(sublist) for sublist in alist]
>
> --
> André Engels, andreengels at gmail.com
>
Thanks Andre
This works.

-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.....محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington
http://emnawfal.googlepages.com
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090311/2c40053f/attachment.htm>


More information about the Tutor mailing list