5
$\begingroup$

I have associations where the values are nested lists:

assoclist= <|KeyA -> {{a,b,2},{c,d,4},{e,f,3}}, 
KeyB -> {{a,b,1},{c,d,4},{e,f,6}}, KeyC -> {{a,b,2},{c,d,6},{e,f,9}}|>;

Now I need to sort the associations by the total sum of the third elements (here the numbers) in each list so that Key C comes first (total sum = 17), than Key B (11) and Key A (9).

How can I do this?

$\endgroup$
  • 5
    $\begingroup$ SortBy[assoclist, -Total[#[[All, 3]]]&]? (Or use ReverseSortBy and get rid of the minus sign) $\endgroup$ – Sjoerd Smit Aug 30 at 10:53
  • $\begingroup$ @SjoerdSmit: I have tried this before but it did not work. It must have been a typing error or so. However now it works perfectly, thx! $\endgroup$ – M.A. Aug 30 at 11:08
6
$\begingroup$

You may use ReverseSortBy with Total and Composition.

ReverseSortBy[Last@*Total]@assoclist

Hope this helps.

$\endgroup$
  • $\begingroup$ Beautiful use of the Wolfram Language. The absence of specific list indices is very nice. It is also easily extended by changing Last or Total as needed. $\endgroup$ – Lee Aug 30 at 22:19
4
$\begingroup$

E.g:

assoclist[[Reverse[Ordering[Total[assoclist[[All, All, 3]]]]]]]
$\endgroup$
2
$\begingroup$

With Transpose:

assoclist // 
  Map[Transpose] // 
  ReverseSortBy[Total@*Last] // 
  Map[Transpose]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.