In Python, I have something like the following (although randomly shuffled):
l = [('a', 'x'),
('a', 'y'),
('a', 'z'),
('b', 'x'),
('b', 'y'),
('b', 'z'),
]
If I call sorted(l), I get a sorted result (like above) which is what one would expect. However, what I need is to forward sort on the first element of the tuple and reverse sort on the second element. In other words, I would like the following result:
l = [('a', 'z'),
('a', 'y'),
('a', 'x'),
('b', 'z'),
('b', 'y'),
('b', 'x'),
]
In Python2.x, there exists a cmp parameter that can be passed to sorted() to achieve this result, but Python3 no longer has this. It has only a key parameter. Is there any way to achieve the desired sort order using only the key parameter?
I know I can define a whole new class to wrap my tuples, or use something like functools.cmp_to_key (which also creates a wrapper class), but that all seems heavy handed for such a simple operation. Is there no other recourse?
edit: I should add that the strings won’t all be one-character strings and that, in some cases, the list of tuples contain non-string data [i.e. (basestring, datetime)].
Sorting in Python is stable as of Python 2.2.
So, you can sort by the second value first with the reverse flag on:
Then you can sort by the first value: