Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorted function using compare function

I'd like to sort a 2D list where each "row" is of size 2, like that for example

[[2,5],[2,3],[10,11]]

These rows represent ranges in fact, so Its always [a,b] where a <= b

I want to sort it exactly this way, each element of the list being a 2-list, I'd have (by order of priority): [a1, b1] compared to [a2, b2]

 1. If a1 < a2 do not permute
 2. If a1 > a2 permute
 3. If a1 == a2 then permute if (b1 - a1) > (b2 - a2)

What I find kind of stupid is that python doesnt allow anymore for comparison functions. Instead it uses a key function. Theres no way I can make a valid key with that as I base my comparison on two parameters, the numeric value of 'a' (which prevails) and then length of the range (b - a).

How can I sort this? I mean, without calling two times sorted() or something, which in my opinion is plain ugly.

Is it even possible? Or is there something I don't see?

Thanks!

like image 955
Yannick Avatar asked Jul 15 '15 05:07

Yannick


People also ask

How does the compare function work in sort?

The purpose of the compare function is to define an alternative sort order. When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value. If the result is negative a is sorted before b .

What is the difference between sort () and sorted () function explain with example?

sort() will sort the list in-place, mutating its indexes and returning None , whereas sorted() will return a new sorted list leaving the original list unchanged. Another difference is that sorted() accepts any iterable while list. sort() is a method of the list class and can only be used with lists.

What does sorted () use in Python?

The Python sorted() uses the Timsort algorithm which is a hybrid sorting algorithm, derived from merge sort and insertion sort.


1 Answers

While there are cases that can't be handled by a key. This is not one of them. The solution is to make the key function return a tuple

>>> L = [[2, 5], [2, 3], [10, 11]]
>>> sorted(L, key=lambda x:(x[0], x[1] - x[0]))
[[2, 3], [2, 5], [10, 11]]
like image 54
John La Rooy Avatar answered Oct 26 '22 17:10

John La Rooy