MathGroup Archive 2003

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

Search the Archive

Re: split a list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg40567] Re: [mg40515] split a list
  • From: Daniel Lichtblau <danl at wolfram.com>
  • Date: Thu, 10 Apr 2003 03:39:44 -0400 (EDT)
  • References: <200304090530.BAA08306@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Roberto Brambilla wrote:
> 
> Hi,
> 
> I have a list (very long, thousands, and unsorted) of numbers r={n1,n2...}
> and for a given a number m  I want to split it in the two sublists
> (unsorted, same order) u={elements<m], v={elements>m}.
> Now I use this *old-style*  method:
> 
> u = v = {};
> For[i = 1, i <= Length[r], i++,
>   tmp = r[[i]];
>   If[tmp > m , AppendTo[u, tmp], AppendTo[v, tmp]];
>   ]
> 
> Any suggestion for a more efficient (and elegant) method?
> Also oneliners are well accepted.
> 
> Many thanks, Roberto
> 
> Roberto Brambilla
> CESI
> Via Rubattino 54
> 20134 Milano
> tel +39.02.2125.5875
> fax +39.02.2125.5492
> rlbrambilla at cesi.it

Here are some possibilities. We'll demonstrate with a list of a million
real numbers.

ll = Table[Random[],{10^6}];

One method is to use Select to split the list.

In[76]:= Timing[ss1 = {Select[ll,#<.5&],Select[ll,#>=.5&]};]
Out[76]= {7.82 Second, Null}

You can instead iterate over the list, throwing elements into either of
two sublists as appropriate. Below are two methods for this, one using
the new Sow/Reap construction and the other building nested lists and
flattening when finished.

In[77]:= Timing[ss2 = Flatten[Experimental`Reap[Scan[
  If[#<.5, Experimental`Sow[#,s1], Experimental`Sow[#,s2]]&, ll],
  {s1,s2}],1];]  
Out[77]= {6.93 Second, Null}

In[78]:= Timing[ss3 = Module[{s1={},s2={}},
  Scan[If[#<.5, s1={s1,#}, s2={s2,#}]&, ll];
  {Flatten[s1],Flatten[s2]}];]                    
Out[78]= {10.83 Second, Null}

In[79]:= ss1===ss2===ss3
Out[79]= True

By the way, the third method above is actually discussed in the notes
for AppendTo in the Mathematica Reference Guide at the back of The
Mathematica Book.

Daniel Lichtblau
Wolfram Research


  • References:
    • split a list
      • From: Roberto Brambilla <rlbrambilla@cesi.it>
  • Prev by Date: Re: split a list
  • Next by Date: Re: split a list
  • Previous by thread: Re: split a list
  • Next by thread: Re: split a list