2
$\begingroup$

I have a List of elements and I need to pick the element which have the maximum or minimum for the third element and the first and second must be equal e.g.

list={{0,2,1}, {0,2,2},{0,2,3},{0,3,0},{1,2,0},{2,2,0},{2,2,1}} 

to ouput

min={{0,2,1}, {2,2,0},{0,3,0},{1,2,0}} or max={{0,2,3},{2,2,1},{0,3,0},{1,2,0}}

Thanks

$\endgroup$
4
  • $\begingroup$ Your output doesn't seem to be consistent with your criteria: in 'min', {0, 2, 1} doesn't have equal first and second elements, and 1 is not the minimum of the three; in 'max', {0, 2, 3} doesn't have he first two elements the same. Can you clarify? $\endgroup$
    – march
    Commented Jan 29, 2020 at 17:02
  • $\begingroup$ I actually meant the first element of the nth element and the second element of the mth element.. so {x,y,z} and {x,y,p} share the the same first two sub-elements. Apologies for the unclear exposition $\endgroup$
    – dadelutz
    Commented Jan 29, 2020 at 17:06
  • $\begingroup$ should {0, 2, 3} appear in min? And the second {0, 2, 3} in max is a typo? $\endgroup$
    – kglr
    Commented Jan 29, 2020 at 18:14
  • $\begingroup$ Just corrected it $\endgroup$
    – dadelutz
    Commented Jan 29, 2020 at 18:16

1 Answer 1

7
$\begingroup$

You can use GatherBy, SplitBy or GroupBy as follows:

min1 = First /@ GatherBy[Sort@list, Most]

{{0, 2, 1}, {0, 3, 0}, {1, 2, 0}, {2, 2, 0}}

max1 = Last /@ GatherBy[Sort@list, Most]

{{0, 2, 3}, {0, 3, 0}, {1, 2, 0}, {2, 2, 1}}

Alternatively,

min2 = First /@ SplitBy[Sort@list, Most];
max2 = Last /@ SplitBy[Sort@list, Most];

min3 = First@*MinimalBy[Last] /@ GatherBy[list, Most];
max3 = First@*MaximalBy[Last] /@ GatherBy[list, Most];

min4 = Values@GroupBy[Sort@list, Most, First];
max4 = Values@GroupBy[Sort@list, Most, Last];

min5 = Values@GroupBy[list, Most, First@*MinimalBy[Last]];
max5 = Values@GroupBy[list, Most, First@*MaximalBy[Last]];

Equal[min1, min2, min3, min4, min5]

True

Equal[max1, max2, max3, max4, max5]

True

$\endgroup$
3
  • $\begingroup$ Thanks, but does not actually do what I want. My question is not really clear. What I mean is that if there are {x,y,z}, {x,y,p}, so x and y are common, I need to output either the min(z,p) or the max (z,p). If there are no multiplicities I just need to print the sub element. Apologies for the unclearness - I edited the original question to make it clearer $\endgroup$
    – dadelutz
    Commented Jan 29, 2020 at 17:59
  • $\begingroup$ @dadelutz, please see the updated version. $\endgroup$
    – kglr
    Commented Jan 29, 2020 at 18:23
  • $\begingroup$ It works just fine. Thanks! $\endgroup$
    – dadelutz
    Commented Jan 29, 2020 at 18:27

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.