user163911
user163911

Reputation: 189

Python 3.3 Sorting a tuple list with multiple keys

I'm having a bit of a problem (encountered during a Project Euler problem) in that I have a list of lists of tuples e.g.

  [...
    [(-119, 359), (668, -609), (-358, -494)], 
    [(440, 929), (968, 214), (760, -857)], 
    [(-700, 785), (838, 29), (-216, 411)], 
    [(-770, -458), (-325, -53), (-505, 633)],
  ...] 

What I want to do is sort them by the tuple with the smallest first value, but if they are equal to then compare the second values and order by the smallest of these. I've been looking about and can't seem to find a way to do this. The only thing I have found is the old python 2.x version of sorted where it is given a cmp argument.

Any help would be much appreciated,

Regards,

Ybrad

Edit:

I just realised the above is worded slightly incorrectly. What I want to do is sort the tuples within each sub-list, not the list of lists as a whole.

Upvotes: 0

Views: 219

Answers (1)

sshashank124
sshashank124

Reputation: 32189

You can very easily do that as:

a = [sorted(i) for i in a]

>>> print a
[[(-358, -494), (-119, 359), (668, -609)],
 [(440, 929), (760, -857), (968, 214)],
 [(-700, 785), (-216, 411), (838, 29)],
 [(-770, -458), (-505, 633), (-325, -53)]]

For your second request, you can do it as:

a = [sorted(i, key=lambda i: (i[0], -i[1])) for i in a]

Upvotes: 1

Related Questions