4
$\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
    $\begingroup$ e.g. SequenceCases[data, {x_List, {E, ___}} :> x] $\endgroup$ – C. E. Apr 22 at 20:27
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$
5
$\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$

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.