Consider list1
to be the output obtained from evaluating Values[list]
, as displayed in the question.
After evaluating
Apply[
Through[{First, Rest}[Reverse[Sort[{##}]]]] &,
list1, {2}]
we obtain
{
{{3, {2, 1}}, {7, {6}}, {5, {}}},
{{9, {8, 7, 6, 3}}, {5, {3, 2, 1}}, {6, {}}},
{{4, {2}}, {4, {}}, {5, {3, 3}}}
}
Apply
allows us to apply a function on every sub-list in list1
ie the output of Apply[f[{##}]&,list1,{2}]
is:
{
{f[{3, 1, 2}], f[{6, 7}], f[{5}]},
{f[{7, 8, 6, 9, 3}], f[{1, 5, 3, 2}], f[{6}]},
{f[{2, 4}], f[{4}], f[{3, 5, 3}]}
}
Instead of applying a generic function like f[{##}]&
we need to Sort
the entries of each list and separate the first item from the rest of the list. This is achieved with substituting
Through[{First, Rest}[Reverse[Sort[{##}]]]] &
for our generic f
.
Note how, this function first Sort
s the entries of each list in ascending order (default), then it Reverses
the output of Sort
(in order to get the descending sort that is required).
Finally we use Through
to obtain a list of {First[#],Rest[#]}&
items of each sub-list.
As an aside, consider the effect of the preceding function on the first sub-list ie evaluate {First[#],Rest[#]}&@{3, 1, 2}
. The output is, as required, {3,{1,2}}
.
The pairs of properly sorted and separated sub-lists can now be manipulated to produce the required ratios (see question) by applying the following rules
{{n_, {}} -> {0}, {n_, l_} :> l/n}
The first rule will take care of every sub-list with a single entry, while the second rule will produce the required ratios, without risking division-by-{}
unwanted output, since that danger is removed by the application of the first rule.
The notebook code along with the output is given below
Apply[
Through[{First, Rest}[Reverse[Sort[{##}]]]] &,
list1, {2}] /.{
{n_, {}} -> {0},
{n_, l_} :> l/n
}
The output of evaluating the code above is
{
{{2/3, 1/3}, {6/7}, {0}},
{{8/9, 7/9, 2/3, 1/3}, {3/5, 2/5, 1/5}, {0}},
{{1/2}, {0}, {3/5, 3/5}}
}