Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
MapThread[] might be more suitable… –  Guess who it is. yesterday
1  
Now that I think about it, you could also use Inner[] –  Guess who it is. yesterday

5 Answers 5

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}}
share|improve this answer
(#[[;; #2]]) & @@@ Transpose[{dataLis, Flatten@lengthLis}]
share|improve this answer

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}}
share|improve this answer
    
I like Inner[Take, dataLis, lengthLis, Sequence] :-) –  Mr.Wizard yesterday
    
@Mr.Wizard, Yes, I also like it :) –  Shutao Tang yesterday
♯0 = #[[;; #2]] & @@@ ({#, ## & @@@ #2}) &;

♯0[dataLis, lengthLis]
(* {{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}} *)
share|improve this answer
Take @@@ ({dataLis, Flatten@lengthLis}\[Transpose])
(* {{1, 2, 3, 4, 5}, {2, 3, 1}, {4, 5, 6}} *)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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