5
$\begingroup$

I am not good at Mathematica. I have the following list already ordered according to the second part:

list1 = {{3, 2}, {5, 2}, {7, 2}, {7, 4}, {8, 4}, {12, 8}, {94, 8}, {4, 10}, {42, 10}};

I want to select the first elements where the second part gets bigger. The result would be:

list2 = {{3, 2}, {7, 4}, {12, 8}, {4, 10}}
$\endgroup$

3 Answers 3

3
$\begingroup$

One approach goes like this:

First /@ GatherBy[list1, Last]

It turns out that GatherBy can be replaced by SplitBy.

$\endgroup$
2
  • $\begingroup$ Wow! Thank you very much! $\endgroup$
    – user57467
    Dec 18, 2018 at 14:16
  • $\begingroup$ @user57467 Glad to be helpful. $\endgroup$ Dec 18, 2018 at 14:24
3
$\begingroup$

You can also use SequenceReplace:

SequenceReplace[list1, {p : ({_, a_} ..)} :> First[{p}]]

{{3, 2}, {7, 4}, {12, 8}, {4, 10}}

$\endgroup$
1
  • $\begingroup$ This function is still not included in my version. I will study it in the future. Thank you very much! $\endgroup$
    – user57467
    Dec 19, 2018 at 16:10
3
$\begingroup$

This seems to work.

DeleteDuplicatesBy[list1, Last]

{{3, 2}, {7, 4}, {12, 8}, {4, 10}}

$\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.