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

Alan Gauld alan.gauld at btinternet.com
Wed Mar 11 10:44:34 CET 2009


"Emad Nawfal (عماد نوفل)" <emadnawfal at gmail.com> wrote
> How can I extract a specific sublist (??) from a nested list,

Just extract eaach item using indexing. So first extract the sublist,
then from the sublist extract the item.

> if I want to extract the sublist ["ADJ", "good"], or the bigger 
> sublist
> ["NP",["DET", "The"],["ADJ", "good"],["NOUN", "man"]] from the 
> following
> nested list?

Look at the structure of your list:

nested_list = [  "S",         <--- 0
                         [  "NP",    <--------- 1,0
                             [ "DET", "The" ],      <-------1,1,0 / 
1,1,1
                             [ "ADJ", "good" ],     <-------1,2,0 / 
1,2,1
                             [ "NOUN", "man" ]    <-------1,3,0 / 
1,3,1
                         ],
                         [  "VP",   <-------2,0
                             [ "V", "came" ]        <-------2,1,0 / 
2,1,1
                         ]
                     ]
So to extract ['ADJ','good'] we use nested_llist[1][2]
and to extract the lionger list nested_list[1]
and to extract the word 'good'  nested_list[1][2][1]

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list