Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python custom sorting, by the difference in two elements of a tuple

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.

like image 671
MitchellSalad Avatar asked Dec 13 '22 05:12

MitchellSalad


1 Answers

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.

like image 179
kindall Avatar answered Jan 05 '23 00:01

kindall