6
$\begingroup$

Consider a data having the form

data = {{1,7,4,6},{1,6,4,8},{2,4,9,2},{E,...},{1,4,6,3},{4,4,6,2},{E,...},...}

i.e., some number $n_{1}$ of rows followed by row $\{E,...\}$, then some number $n_{2}$ of rows followed by row $\{E,...\}$ and so on.

Could you please tell me how to leave only the last rows before $\{E,\}$, i.e. to obtain

subdata= {{2,4,9,2},{4,4,6,2},...}?
$\endgroup$
1
  • 2
    $\begingroup$ e.g. SequenceCases[data, {x_List, {E, ___}} :> x] $\endgroup$
    – C. E.
    Apr 22, 2019 at 20:27

5 Answers 5

5
$\begingroup$

The most idiomatic solution to this problem is, in my opinion, pattern matching (as Sakra has also answered):

SequenceCases[data, {x_List, {E, ___}} :> x]

{{2, 4, 9, 2}, {4, 4, 6, 2}}

But the problem also lends itself to functional solutions, e.g.:

pairs = Partition[data, 2, 1];
If[#[[2, 1]] == E, #[[1]], Nothing] & /@ pairs

{{2, 4, 9, 2}, {4, 4, 6, 2}}

Or in one go:

BlockMap[If[#[[2, 1]] == E, #[[1]], Nothing] &, data, 2, 1]

{{2, 4, 9, 2}, {4, 4, 6, 2}}

$\endgroup$
6
$\begingroup$

Try SequenceCases:

data = {{1, 7, 4, 6}, {1, 6, 4, 8}, {2, 4, 9, 2}, {E, 1, 2, 3}, 
        {1, 4, 6, 3}, {4, 4, 6, 2}, {E, 4, 5, 6}}
SequenceCases[data, {p_, {E, ___}} :> p]

yields

{{2, 4, 9, 2}, {4, 4, 6, 2}}
$\endgroup$
3
$\begingroup$
data =
  {{1, 7, 4, 6}, {1, 6, 4, 8}, {2, 4, 9, 2}, {e, "..."},
   {1, 4, 6, 3}, {4, 4, 6, 2}, {e, "..."}};

Extract[data, Position[data, {e, _}] - 1]

{{2, 4, 9, 2}, {4, 4, 6, 2}}

$\endgroup$
3
$\begingroup$
data = {{1, 7, 4, 6}, {1, 6, 4, 8}, {2, 4, 9, 2}, {E, 1, 2, 3},
        {1, 4, 6, 3}, {4, 4, 6, 2}, {E, 4, 5, 6}};

Using SequenceSplit:

First /@ SequenceSplit[data, {p_, {Except[E], __}}]

(*{{2, 4, 9, 2}, {4, 4, 6, 2}}*)

Or using Pick and Partition:

First /@ Pick[#, ! FreeQ[#[[2]], E] & /@ #] &@Partition[data, 2, 1]

(*{{2, 4, 9, 2}, {4, 4, 6, 2}}*)    
$\endgroup$
3
$\begingroup$

Using Split:

data = {{1, 7, 4, 6}, {1, 6, 4, 8}, {2, 4, 9, 2}, {e, "..."}, {1, 4, 
    6, 3}, {4, 4, 6, 2}, {e, "..."}};

Split[data, First@#1 =!= e &] // Select[Length@# > 1 &] // 
 Map[Last@*Most]

{{2, 4, 9, 2}, {4, 4, 6, 2}}

$\endgroup$

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.