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

1 Answer 1

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$
1
  • $\begingroup$ Brilliant, thank you! $\endgroup$
    – amator2357
    Commented May 8, 2019 at 10:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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