4
$\begingroup$

Say, we have a list: l = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14} and a corresponding list: v = {2,3,2,3,4}. We want to split l into sublists of certain length of consecutive elements ofl and v basically tells us what that length should be. So, in this case, our output would be:

{{1,2},{3,4,5},{6,7},{8,9,10},{11,12,13,14}}

I have written a function that works:

g[l_List] := Module[{split},
split =Table[, {i,1,Length @ l}];
split[[1]] = Table[i,{i,1,First @ l}];
Table[split[[i+1]] = Table[j,{j,Last @ split[[i]] + 1 ,Total @ l[[1;;i+1]]}], 
{i,1,Length@l - 1}];
split
]

g@v

{{1, 2}, {3, 4, 5}, {6, 7}, {8, 9, 10}, {11, 12, 13, 14}}

But I'm sure this could be done in a nicer, and more importantly, more efficient way. Any hints?

$\endgroup$
  • 1
    $\begingroup$ It might be worth thinking about what happens when Total@v does not equal Length@l. $\endgroup$ – geordie May 8 at 12:07
  • 1
    $\begingroup$ In my case that is always the case, but yeah, it's a valid point. $\endgroup$ – amator2357 May 8 at 12:19
8
$\begingroup$

you can use this built-in

 TakeList[l,v]   

{{1, 2}, {3, 4, 5}, {6, 7}, {8, 9, 10}, {11, 12, 13, 14}}

the above solution works with version 11.3

If you have an older version try

FoldPairList[TakeDrop,l,v]    

{{1, 2}, {3, 4, 5}, {6, 7}, {8, 9, 10}, {11, 12, 13, 14}}

$\endgroup$
  • $\begingroup$ Brilliant, thank you! $\endgroup$ – amator2357 May 8 at 10:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.