Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking ties in Python sort

Tags:

python

sorting

I have a list of tuples, each tuple contains two integers. I need to sort the the list (in reverse order) according to the difference of the integers in each tuple, but break ties with the larger first integer.

Example

For [(5, 6), (4, 1), (6, 7)], we should get [(4, 1), (6, 7), (5, 6)].

My way

I have already solved it by making a dictionary that contains the difference as the key and the tuple as the value. But the whole thing is a bit clumsy.

What is a better way?

like image 294
hola Avatar asked Jul 04 '14 18:07

hola


People also ask

Can you sort a string in Python?

Python sorted() Function You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.

How do you reverse sort a tuple in Python?

In python, to sort list of tuples by the first element in descending order, we have to use the sort() method with the parameter ” (reverse=True) “ which will sort the elements in descending order.

What is difference between sort and sorted in Python?

The main difference between sort and sorted in Python is that sort function returns nothing and makes changes to the original sequence, while the sorted () function creates a new sequence type containing a sorted version of the given sequence.


1 Answers

Use a key function to sorted() and return a tuple; values will be sorted lexicographically:

sorted(yourlst, key=lambda t: (abs(t[0] - t[1])), t[0]), reverse=True)

I'm using abs() here to calculate a difference, regardless of which of the two integers is larger.

For your sample input, the key produces (1, 5), (3, 4) and (1, 6); in reverse order that puts (1, 6) (for the (6, 7) tuple) before (1, 5) (corresponding with (5, 6)).

Demo:

>>> yourlst = [(5, 6), (4, 1), (6, 7)]
>>> sorted(yourlst, key=lambda t: (abs(t[0] - t[1]), t[0]), reverse=True)
[(4, 1), (6, 7), (5, 6)]
like image 137
Martijn Pieters Avatar answered Nov 15 '22 21:11

Martijn Pieters