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!
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 .
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.
The Python sorted() uses the Timsort algorithm which is a hybrid sorting algorithm, derived from merge sort and insertion sort.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With