If I have a list that contains a list that looks like this
['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3]
How can I sort them so that element 0 is sorted descending and element 1 sorted ascending so the result would look like
['b',1] ['b',2] ['b',3] ['a',1] ['a',2] ['a',3]
Using itemgetter I can pass in reverse on element 0 but I then resort against element to of course it ruins the previous sort. I can't do a combined key since it needs to first sort descending and then ascending.
itemgetter
L = [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]] L.sort(key=lambda k: (k[0], -k[1]), reverse=True)
L now contains:
L
[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]
2.1m questions
2.1m answers
60 comments
57.0k users