Yannick
Yannick

Reputation: 862

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!

Upvotes: 6

Views: 718

Answers (1)

John La Rooy
John La Rooy

Reputation: 304147

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]]

Upvotes: 5

Related Questions