# Cut nested lists based in another nested list

I have a list of data with nested lists of different length in the following format:

dataLis={{1,2,3,4,5,6,7,5,4},{2,3,1,5},{4,5,6,7,7,8,9}}

Now I have calculated the maximal possible length of all nested lists (based on another data set) and formated that list in the following format

lengthLis={{5},{3},{3}}

Now I would like to cut the dataLis based on lengthLis. I tried the following formula

Outer[Take,dataLis, -lengthLis]

but it does not work. Does anyone have a hint?

• MapThread[] might be more suitable… Commented May 4, 2015 at 17:02
• Now that I think about it, you could also use Inner[] Commented May 4, 2015 at 18:59

MapThread is a good tool for this.

dataLis = {{1, 2, 3, 4, 5, 6, 7, 5, 4}, {2, 3, 1, 5}, {4, 5, 6, 7, 7, 8, 9}};
len = {{5}, {3}, {3}};
{{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}}

As mentioned in comment by @Guess who it is, Inner is a good method to realize your purpose

dataLis =
{{1, 2, 3, 4, 5, 6, 7, 5, 4}, {2, 3, 1, 5}, {4, 5, 6, 7, 7, 8, 9}};
lengthLis = {{5}, {3}, {3}};

First@
Inner[Take, dataLis, lengthLis, List]
(*or Inner[Take, dataLis, lengthLis, Sequence] directly*)
{{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}}
• I like Inner[Take, dataLis, lengthLis, Sequence] :-) Commented May 5, 2015 at 9:03
• @Mr.Wizard, Yes, I also like it :)
– xyz
Commented May 5, 2015 at 9:05
(#[[;; #2]]) & @@@ Transpose[{dataLis, Flatten@lengthLis}]
Take @@@ ({dataLis, Flatten@lengthLis}\[Transpose])
(* {{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}} *)

Using TakeList: (* introduced 14 Sep 2017 *)

dataLis = {{1, 2, 3, 4, 5, 6, 7, 5, 4}, {2, 3, 1, 5}, {4, 5, 6, 7, 7,
8, 9}};
len = {{5}, {3}, {3}};

{{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}}

♯0 = #[[;; #2]] & @@@ ({#, ## & @@@ #2}) &;

♯0[dataLis, lengthLis]
(* {{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}} *)

d = {{1, 2, 3, 4, 5, 6, 7, 5, 4}, {2, 3, 1, 5}, {4, 5, 6, 7, 7, 8, 9}};
l = {{5}, {3}, {3}};

MapThread[d[[#1, ;; #2[[1]]]] &, {Range[Length@d], l}]

(*{{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}}*)

Or using ReplaceAll and Table:

d /. x : {__List} :> Table[x[[i, ;; l[[i, 1]]]], {i, Length@x}]

(*{{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}}*)

MapApply came with V 13.1

MapApply[First @* TakeList] @ Transpose[{dataLis, lengthLis}]

{{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}}