6

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!

3
  • When invoking sorted(elements, cmp=func) on python 3.3.3 it gives me "'cmp' is an invalid keyword argument for this function"
    – Yannick
    Jul 15, 2015 at 5:20
  • The docs offer a cmp to key conversion function but it is not all that pretty. Jul 15, 2015 at 5:24
  • 1
    You can also create a class for inner list and override __cmp__ function
    – Ashwani
    Jul 15, 2015 at 5:32

1 Answer 1

5

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]]
4
  • I am curious about cases that can not be solved using key. Do you have some example, please?
    – Delgan
    Jul 15, 2015 at 5:32
  • Much thanks! I second @Delgan, would be nice to know which cases cannot be solved (I wasnt aware tuples was a working solution)
    – Yannick
    Jul 15, 2015 at 6:45
  • @Delgan, Suppose the sublists list were [firstname, surname] I need to sort by surname. Where the surnames are equal I need to sort by firstname - but in reverse. Jul 15, 2015 at 10:47
  • @JohnLaRooy key=lambda x:(x[1], [-ord(i) for i in x[0]]) should work, am I wrong? However, this is probably not great, I wonder what is the proper way for solving this issue.
    – Delgan
    Jul 15, 2015 at 11:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.