Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to sort by a second key in the event that the first key is equal?

Let's say I have the following list.

foo = [["A", 1], ["B", 2], ["C", 1]]

I want to sort by the second element in the list, so I run the following.

foo.sort(key=lambda i: i[1])

Now, foo has the following order.

[['A', 1], ['C', 1], ['B', 2]]

Is there a good way to sort by the first element in the event that the second element in the list is equal? Say the order I want is the following.

[['C', 1], ['A', 1], ['B', 2]]
like image 251
Ayrx Avatar asked Mar 18 '23 15:03

Ayrx


1 Answers

Just set your key to a tuple of the last, then first element. Tuples are automatically sorted in the way you describe (sorting on first element first, then second, and so on).

foo.sort(key=lambda i: (i[1], i[0]))

Note that if you don't absolutely need your original lists to be in the given order, you could sort the original list directly if you could switch the order. If you make your list foo = [[1, "A"], [2, "B"], [1, "C"]] then you could just do foo.sort() and that's it. You could convert your list into that format by doing foo = [reversed(i) for i in foo].

like image 188
BrenBarn Avatar answered Apr 05 '23 23:04

BrenBarn