If you have a simple list of lists as follows:
test = {{1, 2}, {4, 5, 6, 7}, {5, 4, 3}}
How do you ask Mathematica to return the sublist of greatest length?
I've been trying to write a Select command using pure functions without success.
|
If you have a simple list of lists as follows:
How do you ask Mathematica to return the sublist of greatest length? I've been trying to write a |
||||
|
|
|
One possibility:
gives:
If there are two or more sublists that are of 'greatest length' those will also be returned. |
|||||||
|
|
Reasonably fast and quite direct, but returns only one list if there are ties:
More whimsical but catching ties (warning: infix ahead):
Since Arnoud's method tests the fastest for functions that include ties, here is my terse version of it:
|
||||
|
|
|
|
|||
|
|
A solution using
This solution and Arnoud's, as well as J.M.'s ones, are better if we have more lists of maximal length. E.g. for
this returns
Edit Since one would like to know performance issues of various methods I've made a comparison of presented approaches (only for methods which return all longest sublists) on a very long list from the best to the slowest. On smaller lists proportions of timings may slightly change, but in general, the order is preserved.
|
|||||
|
|
Alternatively:
|
|||
|
|
|
If you only want one item from the resulting list, you can use the two-argument form of
|
|||||||
|
|
I sometimes use a little function
You need the largest element by length, so you can evaluate
Note: this is based on the same principle as @Brett's solution, but it is slower. @Brett's and @R.M's exploit the fact that Mathematica sorts by length by default, while my solution explicitly uses The problem with
|
||||
|
|