Reputation: 635
The title is rather confusing but the question is rather straightforward.
Say I have a list of tuples like so:
d = [('said', 12), ('that', 12), ('electricity', 11), ('was', 10), ('the', 51), ('zealand', 9), ('for', 13), ('new', 12), ('power', 14), ('transmission', 14), ('and', 9)]
I want to sort the list so that it is ordered by the value in descending order. However I want ties to be sorted alphabetically by key.
I.e for the above list 'zealand' and 'and' both have the same value. But in the sorted list output I want 'and' to appear before 'zealand'.
I tried doing
d.sort(key=operator.itemgetter(1, 0), reverse=True)
print(d)
This gives me the output
[('the', 51), ('transmission', 14), ('power', 14), ('for', 13), ('that', 12), ('said', 12), ('new', 12), ('electricity', 11), ('was', 10), ('zealand', 9), ('and', 9)]
However the tuple ('zealand', 9)
appears before ('and', 9)
when in reality I want ('and', 9)
to appear before ('zealand', 9)
since 'and' is before 'zealand' alphabetically.
What would be the best way to do this type of sort where it is reverse in one direction for the value and not-reverse for the key.
Please let me know if you need any more information.
Thank you for your time.
Upvotes: 3
Views: 1423
Reputation: 114569
In this specific case the solution is simple...
L.sort(key = lambda x : (-x[1], x[0]))
I'm returning as sorting key a tuple where the first element is the opposite of the value and the second element is the string. This way the sort will be descending by value and alphabetically ascending when the value is the same.
Upvotes: 9