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

Andre Engels andreengels at gmail.com
Wed Mar 11 12:47:52 CET 2009


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


More information about the Tutor mailing list