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]]
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With