Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's an approach that relies on <code>Transpose</code>:</p> <pre><code>maxBy = #1[[Position[t = Transpose[#1][[#2]], Max[t]][[All, 1]]]] &amp;; </code></pre> <p>For example: list = {{4, 3}, {5, 10}, {20, 1}, {3, 7}};</p> <pre><code>maxBy[list, 1] (* {{20, 1}} *) maxBy[list, 2] (* {{5, 10}} *) </code></pre> <p>It can handle more than two elements per sublist, provided that the sublists are all the same length.</p> <pre><code>r:=RandomInteger[{-10^5,10^5}]; list3=Table[{r,r,r},{j,10^2}]; (* 3 numbers in each sublist *) list9=Table[{r,r,r,r,r,r,r,r,r},{j,10^2}]; (* 9 numbers *) maxBy[list3, 2] (* Find max in position 2 of list3 *) (* {{-93332, 99582, 4324}} *) maxBy[list9, 5] (* Find max in position 5 of list9 *) (* {{7680, 85508, 51915, -58282, 94679, 50968, -12664, 75246, -82903}} *) </code></pre> <p>Of course, the results will vary according to the random numbers you have generated.</p> <p><strong>Edit</strong></p> <p>Here's some timing data for large lists. <code>SortBy</code> is clearly slower. but doesn't seem as influenced by the number of elements in each sublist. First, my <code>maxBy</code> code followed by <code>SortBy</code>:</p> <p><img src="https://i.stack.imgur.com/pia4A.png" alt="Timing comparison"></p> <p>Using the same list2, here's some timing data for Yoda's code. Although his routine is also called maxBy, it is his that produced the output that follows:</p> <p><img src="https://i.stack.imgur.com/heCLz.png" alt="Yoda"></p> <p>Again, with the same list2, some data for Belisarius' code:</p> <p><img src="https://i.stack.imgur.com/0LCAK.png" alt="Belisarius"></p> <p>His second suggestion is the fastest of all tested.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload