Re: split a list
- To: mathgroup at smc.vnet.net
- Subject: [mg40542] Re: [mg40515] split a list
- From: Dr Bob <majort at cox-internet.com>
- Date: Wed, 9 Apr 2003 20:27:04 -0400 (EDT)
- References: <200304090530.BAA08306@smc.vnet.net>
- Reply-to: majort at cox-internet.com
- Sender: owner-wri-mathgroup at wolfram.com
This is a beautiful application for Sow and Reap. << Experimental` testList[n_Integer] := Array[Random[] &, n] trial[n_Integer] := {testList@n, Random[]} breakList[test_List, break_] := Reap[If[# < break, Sow[#, 1], Sow[#, 2]] & /@ test] trial@30 breakList @@ % That version may not be ideal, because if all elements are on the same side of the break point, you get only one list back -- not two, with one of them empty. If that's a concern (but with thousands of elements it may never come up), this function fixes it: breakList2[test_List, break_] := Rest /@ Reap[Sow[0, #] & /@ {1,2}; If[# < break, Sow[#, 1], Sow[#, 2]] & /@ test] Here's another solution to that problem: breakList3[test_List, break_] := Flatten /@ Reap[If[# < break, Sow[#, 1], Sow[#, 2]] & /@ test, {1, 2}] Try lists of length 4 or 5, to see the strange cases. Take out Flatten in the last function, and you'll see why it was added. Bobby On Wed, 9 Apr 2003 01:30:31 -0400 (EDT), Roberto Brambilla <rlbrambilla at cesi.it> 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 > > > -- majort at cox-internet.com Bobby R. Treat
- References:
- split a list
- From: Roberto Brambilla <rlbrambilla@cesi.it>
- split a list