# How to leave only the following strings?

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},...}?

• e.g. SequenceCases[data, {x_List, {E, ___}} :> x] Apr 22, 2019 at 20:27

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}}

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}}

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}}

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}}*)


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}}