Group list of lists by Total
Sort@GatherBy[{{0, 1}, {4}, {0, 0, 1}, {2, 0, 1}, {3, 0, 0}, {3, 1}, {0, 0, 0, 4}}, Total]
To make sure Sort
always gets it right:
Sort[GatherBy[n, Total], Less[Total@First[#], Total@First[#2]] &]
A simple approach is to just use:
GatherBy[SortBy[list,Total],Total]
This ensures that they appear in the correct order since they are gathered based on the appearance of the first element. In each sublist with the same total, they will be ordered based on OrderedQ
, which puts them in order of number of elements afaik.
To verify that it works out:
listA={{0,1},{4},{0,0,1},{2,0,1},{3,0,0},{3,1},{0,0,0,4}};
listB={{0, 0, 0, 0, 0, 1}, {4}, {0, 0, 0, 0, 1}, {2, 0, 1}, {3, 0, 0}, {3, 1}, {0, 0, 0, 4}};
verify[v_] := Total[First[#]] & /@ v
verify@GatherBy[SortBy[listA, Total], Total]
verify@GatherBy[SortBy[listB, Total], Total]
(* {1,3,4} *)
(* {1,3,4} *)
I would write it like this:
list ~SortBy~ {Total} ~SplitBy~ Total
Note that putting the SortBy
function inside a list (i.e. {Total}
instead of just Total
) means that SortBy
will give a stable sort, so elements with the same total will stay in the order they were in the original list.