Re: Partition a list into sublists of unequal size

*To*: mathgroup at smc.vnet.net*Subject*: [mg83946] Re: Partition a list into sublists of unequal size*From*: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>*Date*: Wed, 5 Dec 2007 07:11:13 -0500 (EST)*Organization*: The Open University, Milton Keynes, UK*References*: <fj37cv$hq0$1@smc.vnet.net>

antf wrote: > 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? The following might not be the simpler way you were expected; still, it might be a source of inspiration :) lst = {1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0}; myPart[target_List, source_List] /; Length@target == Length@source := Take[target, #] & /@ Thread[{PadLeft[Most@# + 1, Length@#, 1], #} &[ Flatten@Position[source, 1]]] myPart[lst, lst] returns {{1}, {0, 0, 1}, {0, 0, 1}, {1}, {0, 1}, {0, 0, 0, 0, 1}} (Note that in the case where the source and target lists are the same Split[lst, (#1 != 1) &] would be enough to get the desired result.) Also, in the example you provided, the last sequence of running zeros is not taken into account. Is this desired? Regards, -- Jean-Marc