Re: Partition a list into sublists of unequal size
- To: mathgroup at smc.vnet.net
- Subject: [mg83964] Re: Partition a list into sublists of unequal size
- From: Szabolcs Horvát <szhorvat at gmail.com>
- Date: Wed, 5 Dec 2007 07:20:45 -0500 (EST)
- References: <fj37cv$hq0$1@smc.vnet.net>
antf wrote: > Hello, > > I have a list that looks like the following: > > list={1,0,0,1,0,0,1,1,0,1,0,0,0,0,1,0} > > I then find the positions of the 1s in the list: > > positions = Flatten@Position[list,1] > > {1,4,7,8,10,15} > > I then want to partition a third list into sublists so that the first > sublist is from index 1;;1, the second sublist is from index 2;;4, the > third sublist is from index 5;;7, the fourth sublist is just element > 8, etc. > > Currently, I use Partition on the positions sublist with overlap as > in: > > Partition[Join[{1},positions],2,1] > > {{1,1},{1,4},{4,7},{7,8},{8,10},{10,15}} > > I then use this list to partition the target list by Mapping Take to > each element of this list and adjusting the first index appropriately. > > I am sure there must be a simpler way to do this. Can anyone tell me > how to do this operation? This isn't really simpler ... but here's another way: In[1]:= l1 = RandomInteger[{0, 1}, {20}] Out[1]= {1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1} In[2]:= l2 = Accumulate[l1] - l1 Out[2]= {0, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 9, 10, 10, 11, 11} In[3]:= l3 = Range[20] (* the list to be partitioned *) Out[3]= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, \ 18, 19, 20} In[4]:= Split[Transpose[{l2, l3}], First[#1] == First[#2] &][[All, All, 2]] Out[4]= {{1}, {2, 3, 4, 5, 6}, {7}, {8}, {9}, {10}, {11}, {12, 13}, {14}, {15, 16}, {17, 18}, {19, 20}} -- Szabolcs