I have a list of tuples of format:
(node1, node2, weight)
What I want to do is sort this tuple so that the the nodes with higher weight are at the top
for example
(A,B,2)
(A,C,5)
(C,A,2)
should give me
(A,C,5)
(A,B,2)
(C,A,2)
The first node is sorted alphabetically.
Second node as per the decreasing weight ranks.
This should work just fine:
Of course, we can avoid the lambda by:
If you want to sort on multiple conditions, you can create interesting functions to return tuples (tuples will sort by first index, then second, then third …), or you can use the fact that python’s sorts are guaranteed to be stable. So, if you want your list to be sorted primarily by weight and then by node name, you just sort first by node name and then by weight. (the backwards order is a little counter intuitive).
If I understand your question (after a re-read and seeing some of the comments here) you’re sort can be done as follows:
This sorts primarily by weight (high numbers first) and then by node1 alphabetically for objects with the same weight.
Note that this only works if you can negate
x[2]to make high numbers appear first in the sort (it wouldn’t work for strings for example). A more reliable way to accomplish the same thing (although less efficient?) would be: