SortBy first element then second element, and so on?

If your list contains only positive elements, then this may work.

SeedRandom@1
n = 100;
list = TakeList[RandomInteger[{1, 10}, n], RandomInteger[{1, 7}, 10]]

{{2, 5, 1}, {8, 1, 1, 9, 7}, {1, 5, 2, 9, 6}, {2, 2, 2, 4, 3, 2, 7}, {1, 3, 7, 5, 6, 5, 4}, {1}, {2, 4, 6, 4, 1}, {4, 3}, {4, 10, 6}, {2}}

max = Length /@ list // Max;
Sort[PadRight[#, max] & /@ list] // DeleteCases[#, 0, Infinity] &

{{1}, {1, 3, 7, 5, 6, 5, 4}, {1, 5, 2, 9, 6}, {2}, {2, 2, 2, 4, 3, 2, 7}, {2, 4, 6, 4, 1}, {2, 5, 1}, {4, 3}, {4, 10, 6}, {8, 1, 1, 9, 7}}

Edit:

SeedRandom@1
n = 100;
list = TakeList[RandomInteger[10, n], RandomInteger[{1, 10}, 10]]

{{1, 4, 0, 7, 0}, {0, 8, 6, 0, 4, 1, 8, 5}, {1}, {1, 1, 3, 2, 10, 1, 6, 0}, {2, 6, 4, 5, 4, 3, 0, 1}, {3, 5, 3, 0}, {3, 2, 3, 9, 5, 1}, {5, 2, 3, 9, 1, 0}, {4}, {4, 1, 5, 2, 7, 9}}

 smallNumber = -100;
 max = Length /@ list // Max;
 Sort[PadRight[#, max, smallNumber] & /@ list] // DeleteCases[#, smallNumber, Infinity] &

{{0, 8, 6, 0, 4, 1, 8, 5}, {1}, {1, 1, 3, 2, 10, 1, 6, 0}, {1, 4, 0, 7, 0}, {2, 6, 4, 5, 4, 3, 0, 1}, {3, 2, 3, 9, 5, 1}, {3, 5, 3, 0}, {4}, {4, 1, 5, 2, 7, 9}, {5, 2, 3, 9, 1, 0}}


Like Pillsy I thought to pad the list. In the case given a simpler form works:

lsts = {{1, 6}, {1, 2, 8}, {2}};

lsts[[Ordering @ PadRight @ lsts]]
{{1, 2, 8}, {1, 6}, {2}}

Related examples:

  • Unexpected result {".a", "co", ".m"} from Sort[{".m", ".a", "co"}]
  • Sort strings by natural ordering

If you pad out the lists on the left with $ -\infty$, you ensure that a short list which is a prefix of a long list will come before it, giving you a lexicographic sort. Then you can use Ordering and Part to pull out the old elements.

data = {{1, 6}, {1, 2, 8}, {2}}
With[{n = Max[Length /@ data]},
 Part[data, Ordering[PadRight[#, n, -Infinity] & /@ data]]]

(* {{1, 2, 8}, {1, 6}, {2}} *)

Tags:

Sorting

Order