python - Sort a list of tuples with two tuple entries in opposite order -


hopefully make sense...

i have list of tuples of following form:

list_of_tuples = [('a', 1), ('b', 3), ('b', 2), ('a', 3)] 

the desired output is

sorted_list_of_tuples = [('a', 1), ('b', 2), ('b', 3), ('a', 3)] 

the issue want second entry increasing, , first entry decreasing.

import operator op      sorted_list_of_tuples = sorted(list_of_tuples, key=op.itemgetter(2, 0)) 

this, of course, sorts both fields increasing. can't come cute (i.e., couple of lines) way this. have way accomplish kind of sorting easily?

i seem remember can reference elements of list comprehension inside brackets using _, maybe that's place start?


maybe wasn't clear: integer in case more important. it's order should increasing across list. when there's tie (ie.., second entry equal), want 'b' occur before 'a'.

if can describe key in english, translate function.

i want second entry increasing, , first entry decreasing.

so, key is:

def make_key(my_tuple):     return my_tuple[1], -my_tuple[0] 

except, of course, - doesn't work way on strings, need fancier.

or, maybe not… while first element of each tuple string, second integer, so, can negate key function, , use reverse un-negate it:

def make_key(my_tuple):     return -my_tuple[1], my_tuple[0]  sorted_list_of_tuples = sorted(list_of_tuples, key=make_key, reverse=true) 

if want save few keystrokes:

sorted_list_of_tuples = sorted(list_of_tuples,                                key=lambda x: (x[1], x[0]), reverse=true) 

this isn't trick work here. example, because of strings 1-character strings, ord(x) < ord(y) iff x < y.

but can't think of easy trick—but can think of easy way write comparison function. if it's more readable, way:

def compare_my_tuples(lhs, rhs):             if rhs[1] > lhs[0]: return 1     elif rhs[1] < lhs[0]: return -1     elif rhs[0] > lhs[0]: return -1     elif rhs[0] < rhs[0]: return 1     else: return 0  sorted_list_of_tuples = sorted(list_of_tuples,                                 key=functools.cmp_to_key(compare_my_tuples)) 

or, of course, can split 2 sorts, in steveha's answer. (yes, might take twice long… in apps, won't make difference @ all.)


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -