tags:

views:

63

answers:

2

I have a weird list built in the following way:

[[name_d, 5], [name_e, 10], [name_a, 5]] 

and I want to sort it first by the number (desc) and then, if the number is the same, by the name (asc). So the result I would like to have is:

[[name_e, 10], [name_a, 5], [name_d, 5]]

I tried to think to a lambda function that I can use in the sort method, but I'm not sure I can do it.

A: 

It doesn't need to be a lambda function you pass into the sort method, you can actually provide a real function since they are first-class objects in python.

L.sort(my_comparison_function)

Should work just fine

Daniel DiPaolo
-1 Comparison function goes away in Python 3, whereas the other answer is future proof.
Steven Rumbalski
I thought about this, but how can I write a comparison function that works on two different keys? basically I need a f((x[0],x[1]), (y[0],y[1]))
Giovanni Di Milia
@Steven: what are you talking about? this answer might be useless, but not for the reasons you state. [Read the docs](http://docs.python.org/py3k/library/stdtypes.html#mutable-sequence-types)
SilentGhost
@SilentGhost Maybe I'm misreading, but when I look at the linked docs i see that sort accepts a /key/ function in python 3, but not a /comparison/ function.
Steven Rumbalski
@Steven: and what is key function if not a comparison function?
SilentGhost
@SilentGhost A comparison function is called on pairs of items and "should return a negative integer if self < other, zero if self == other, a positive integer if self > other." Whereas a key function is called once for each item and returns the value(s) you want an item sorted on. See http://wiki.python.org/moin/HowTo/Sorting/ paying attention specifically to sections titled _Key_Functions_ and _The_Old_Way_Using_the_cmp_Parameter_. The key parameter was added in Python 2.4. The cmp parameter was removed in Python 3.
Steven Rumbalski
+4  A: 

This should do it:

l=[[name_d, 5], [name_e, 10], [name_a, 5]]
sorted(l,key=lambda x: (x[1]*-1,x[0]))

Edit: Sort order

Till Backhaus
he needs descending sorting for the number
SilentGhost
this doesn't work in the way I want, because it sorts also the name in desc (or asc) mode
Giovanni Di Milia
@Giovanni: it's not a black box. Do you see how it is solved? and you cannot modify it to suit your problem?
SilentGhost
yeah, `-x[1]` would do
SilentGhost
Corrected the sort order. Like SilentGhost said already - it should have been obvious how to change the order.
Till Backhaus
btw: if you don't want to copy the listL `l.sort(key=lambda...)`
Till Backhaus
@SilentGhost, Sorry, I didn't know that I could invert the sorting with the "-"
Giovanni Di Milia