# Select specific elements of list and pick it

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

• 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? Commented Jan 29, 2020 at 17:02
• 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 Commented Jan 29, 2020 at 17:06
• should {0, 2, 3} appear in min? And the second {0, 2, 3} in max is a typo?
– kglr
Commented Jan 29, 2020 at 18:14
• Just corrected it Commented Jan 29, 2020 at 18:16

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

• 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 Commented Jan 29, 2020 at 17:59