4

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.

MitchellSalad
  • 4,171
  • 8
  • 23
  • 24

5 Answers5

8
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.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • Can you please point me to the official doc? I can't seem to find the function prototype here. http://docs.python.org/tutorial/datastructures.html – shadyabhi Jan 24 '12 at 07:13
  • Thanks for the answer! But... I believe you have the sorting backwards? The largest difference should be first, so either "key=lambda t: t[1] - t[0]" or "key=lambda t[0] - t[1], reverse=True". Anyways, thank you! – MitchellSalad Jan 24 '12 at 07:28
  • I came here looking to sort a list of integers, definetely nothing of the above works, for anyone lost like me go to: https://stackoverflow.com/questions/5314241/difference-between-consecutive-elements-in-list – Mincho Apr 26 '21 at 14:13
2

Since it can be assumed that some_int2 is always bigger than some_int, you just need to use the difference between them as the key for the sorting:

l.sort(key=lambda t: t[1] - t[0])

Example:

>>> l = [(1, 1, 'a'), (2, 0, 'b')]
>>> l.sort(key=lambda t: t[1] - t[0])
>>> l
[(2, 0, 'b'), (1, 1, 'a')]
jcollado
  • 39,419
  • 8
  • 102
  • 133
1
def my_cmp(a,b):
  return cmp(b[1]-b[0], a[1]-a[0])

my_list.sort(my_cmp)
dorsh
  • 23,750
  • 2
  • 27
  • 29
1

With x[0] always larger than x[1]:

lst.sort(key=(lambda x: x[0]-x[1]), reverse=True)

or

lst.sort(key=(lambda x: x[1]-x[0]))
Don O'Donnell
  • 4,538
  • 3
  • 26
  • 27
1

If you're interested in improving your sorting skills, the Python Sorting HOW-TO Guide may be of help. It is loaded with examples. To sort using the difference between two tuple elements, define a key function that computes the desired sort key:

>>> sorted(iterable, key=lambda t: t[1] - t[0], reverse=True)
Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485