I'm new to Python's custom sorting capabilities, but I'm sure the following can be done. I have a list of tuples, and each tuple looks like this:
(some_int, some_int2, string)
I want to sort the list by the descending difference between some_int and some_int2, i.e. the largest difference between these two ints should be at the head of the list. It can safely be assumed that some_int2 is always bigger than some_int.
Thank you all.
mylist.sort(key=lambda t: t[0] - t[1])
Note I'm subtracting them in the "wrong" order, which means that the differences will all come out negative and thereby sort the largest in magnitude to the beginning of the list. If you wanted, you could also subtract them in the "right" order and set reverse=True
:
mylist.sort(key=lambda t: t[1] - t[0], reverse=True)
That might be clearer although a bit more verbose.
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