Finding the maximum from a two dimensional list
Another one:
data = {{1, 2}, {1, 3}, {1, 4}, {2, 2}, {2, 3}, {2, 4}, {2, 5}};
GroupBy[data, First -> Last, Max]
<|1 -> 4, 2 -> 5|>
If you need the result as a list of pairs:
KeyValueMap[List, %]
{{1, 4}, {2, 5}}
Since you specified "Is there an efficient method?"
GatherBy[Sort@list, First][[All, -1]]
(here list
is your list or variable the list is assigned to).
This should outperform the accepted solution by at least an order of magnitude.
Slightly more verbose, but even quicker:
With[{g = GatherBy[list, First]},
Transpose[{g[[All, 1, 1]], Max /@ g[[All, All, 2]]}]]
Here's a variation of @sjoerd's answer:
data={{1,2},{1,3},{1,4},{2,2},{2,3},{2,4},{2,5}};
ResourceFunction["GroupByList"][data[[All,2]],data[[All,1]],Max]
<|1 -> 4, 2 -> 5|>
For large datasets, this will be much faster than GroupBy
:
data = RandomInteger[10000, {10^6, 2}];
r1=ResourceFunction["GroupByList"][data[[All,2]], data[[All,1]], Max];//AbsoluteTiming
r2=GroupBy[data, First->Last, Max];//AbsoluteTiming
r1===r2
{0.10384, Null}
{0.514609, Null}
True
This approach is also slightly faster than @ciao's.