6

I have a list of tuples:

li = [('fink', 3), ('flip', 3), ('flock', 4), ('foo', 12), ('foot', 20), ('football', 20), ('futz', 10), ('flip', 3), ('flank', 3), ('flop', 3)]

How can I sort the list by descent number first and then alphabetically descending? The results would be:

('foot', 20)
('football', 20)
('foo', 12)
('futz', 10)
('flock', 4)
('fink', 3)
('flip', 3)
('flake', 3)
('flop', 3)

from operator import itemgetter

sorted_li = sorted(li, key=itemgetter(1,0), reverse=True)

While the above code sorts by descending number correctly, the words are not sorted alphabetically.

1

3 Answers 3

11

This is too complicated for a single itemgetter. Use lambda instead:

sorted_li = sorted(li, key=lambda x: (-x[1], x[0]))

It is about the same speed as two consecutive sorts using itemgetter, but it is less code and probably more readable.

Sign up to request clarification or add additional context in comments.

2 Comments

This works because you're able to use the fact a sort element is a number. What if both were strings?
@JonClements He would use your solution :)
6

As Python's sort is stable, it's easiest to sort twice:

sorted_li  = sorted(li, key=itemgetter(1), reverse=True)
sorted_li.sort(key=itemgetter(0))

Comments

0

As Python's sort is stable, it's easiest to sort twice:

sorted_li  = sorted(li, key=itemgetter(0))
sorted_li.sort(key=itemgetter(1), reverse=True)

but attention that you must use your lowest priority order at first , then the others base on the priority. the highest priority order must be the last one. it is the most important thing that you have to consider when you try to use Sorted function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.