MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: List Partition

  • To: mathgroup at smc.vnet.net
  • Subject: [mg53941] Re: [mg53895] List Partition
  • From: John Kiehl <john.kiehl at soundtrackny.com>
  • Date: Fri, 4 Feb 2005 04:12:26 -0500 (EST)
  • Reply-to: John Kiehl <john.kiehl at soundtrackny.com>
  • Sender: owner-wri-mathgroup at wolfram.com


On Wednesday, February 2, 2005 6:25 AM, zak <chocolatez at gmail.com> wrote:
>what could i do to partition the list:
>a={cat,E,in,the,hat,E,okay,fine,E}
>into
>a={{cat},{{in},{the},{hat}},{{okay},{fine}}}
>
>ie:  every word in a sublist , and E determine the end of a
>sentence
>(a bigger list).
>zak
>
>

In[16]:=  a={cat,E,in,the,hat,E,okay,fine,E}
Out[16]=    {cat,E,in,the,hat,E,okay,fine,E}
 
 
This solution is an automation of this basic idea.  

In[61]:=  Part[a,{1}]
Out[61]=  {cat}

In[62]:=  Part[a,{3,4,5}]
Out[62]=  {in,the,hat}

In[63]:=  Part[a,{7,8}]
Out[63]=  {okay,fine}

The "Position" of E in the original list will be used to calculate the start and end of each sub-list.

(*-------------------------------------------------*)
(* so, first put brackets around each element as requested *)
In[20]=    aa=Map[List,a]
Out[20]=  {{cat},{E},{in},{the},{hat},{E},{okay},{fine},{E}}

(* in general, we want to find positions of {E} in list *)
In[30]=    pos = Position[aa,{E}]//Flatten
Out[30]=   {2,6,9}

(* one less than pos will be end of each sublist *)
In[33]:=   last=pos-1
Out[33]:=   {1,5,8}

(* one more than pos will be start of each sublist, 
  also drop last value and prepend a 1 *)
In[41]:=   first=Drop[Flatten[{1,pos}],-1]
Out[41]=   {1,3,7}

(* pair these up *)
In[45]:=   t=Transpose[{first,last}]
Out[45]=   {{1,1},{3,5},{7,8}}

(* map Part[...] over our list t *)
In[52]:=   Part[aa,Range[Sequence @@ #]]& /@ t
Out[52]=   {{{cat}},{{in},{the},{hat}},{{okay},{fine}}}



  • Prev by Date: Re: Problem with a sum
  • Next by Date: Re: Matrix equations
  • Previous by thread: Re: List Partition
  • Next by thread: Re: List Partition