2
$\begingroup$

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?

$\endgroup$
5
$\begingroup$

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}}
$\endgroup$
3
$\begingroup$
(#[[;; #2]]) & @@@ Transpose[{dataLis, Flatten@lengthLis}]
$\endgroup$
3
$\begingroup$

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}}
$\endgroup$
  • $\begingroup$ I like Inner[Take, dataLis, lengthLis, Sequence] :-) $\endgroup$ – Mr.Wizard May 5 '15 at 9:03
  • $\begingroup$ @Mr.Wizard, Yes, I also like it :) $\endgroup$ – xyz May 5 '15 at 9:05
1
$\begingroup$
♯0 = #[[;; #2]] & @@@ ({#, ## & @@@ #2}) &;

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

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.