sorting - How can I sort tuples by reverse, yet breaking ties non-reverse? (Python) -
if have list of tuples:
results = [('10', 'mary'), ('9', 'john'), ('10', 'george'), ('9', 'frank'), ('9', 'adam')]
how can sort list might see in scoreboard - such sort score biggest smallest, break ties alphabetically name?
so after sort, list should like:
results = [('10', 'george'), ('10', 'mary'), ('9', 'adam'), ('9', 'frank'), ('9', 'john')]
at moment can results.sort(reverse=true)
, breaks ties reverse alphabetically too...
any appreciated. thanks!
the simplest way achieve want use fact python sort stable. allows first sort alphabetically , score:
in [11]: results = [(10, 'mary'), (9, 'john'), (10, 'george'), (9, 'frank'), (9, 'adam')] in [12]: results.sort(key=lambda x: x[1]) in [13]: results.sort(key=lambda x: x[0], reverse=true) in [14]: results out[14]: [(10, 'george'), (10, 'mary'), (9, 'adam'), (9, 'frank'), (9, 'john')]
the first sort sorts alphabetically, in ascending order. second sort sorts score, in descending order, maintaining relative order of elements equal score.
you can more complex sorts. remember must first sort secondary key, , first key. (if have 3 keys, first sort third, second, , lastly main key).
if don't want call sort
twice you'll have write more complex key
function. like:
in [50]: def key(elem): ...: return elem[0], [-ord(c) c in elem[1]] in [51]: sorted(results, key=key, reverse=true) out[51]: [(10, 'george'), (10, 'mary'), (9, 'adam'), (9, 'frank'), (9, 'john')]
in particular, every time have sorted in lexicographic order(such strings, tuples, lists etc.), can invert order changing sign elements.
Comments
Post a Comment