# 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… May 4, 2015 at 17:02
• Now that I think about it, you could also use Inner[] May 4, 2015 at 18:59

## 5 Answers

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}};
MapThread[Take, {dataLis, Flatten @ len}]

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

(#[[;; #2]]) & @@@ Transpose[{dataLis, Flatten@lengthLis}]


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] :-) May 5, 2015 at 9:03
• @Mr.Wizard, Yes, I also like it :)
– xyz
May 5, 2015 at 9:05
♯0 = #[[;; #2]] & @@@ ({#, ## & @@@ #2}) &;

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

Take @@@ ({dataLis, Flatten@lengthLis}\[Transpose])
(* {{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}} *)