0

I need to sort a list of tuples (length 2) but specifically need it to sort by second value descending and then by first value ascending. i.e. (0,1)<(1,1)<(1,0)

I think I could do it without too much trouble with a comparison function, but would like to know if it's doable with a key function.

  • Do the answers to this [question](https://stackoverflow.com/questions/3121979/how-to-sort-a-list-tuple-of-lists-tuples-by-the-element-at-a-given-index) help at all? – quamrana Aug 08 '23 at 15:49
  • What is the difference between a "comparison function" and a "key function"? I'm not even sure what you are asking. – John Gordon Aug 08 '23 at 15:52
  • @JohnGordon A key function takes a single parameter and returns a number which is used for sorting. A comparison function takes two parameters and returns -1, 0, or 1 if the first argument is less than, equal to, or greater than the second respectively. As of python3, you could no longer use 'cmp=____' as an optional argument in sort(). Only keys are directly supported now. – Mckay Holmes Aug 08 '23 at 17:15
  • @quamrana Not really. using something like sort(L,key=itemgetter(1,0),reverse=True) would sort both values descending – Mckay Holmes Aug 08 '23 at 17:17
  • @JohnGordon Contrast [comparison functions](https://docs.python.org/3/howto/sorting.html#comparison-functions) and [key functions](https://docs.python.org/3/howto/sorting.html#key-functions) – Stef Aug 08 '23 at 18:17

1 Answers1

1

You could use a lambda key as follows:

tlist = [
    (1,1),
    (0,1),
    (1,0)
]

print(sorted(tlist, key=lambda x: (-x[1], x[0])))

Output:

[(0, 1), (1, 1), (1, 0)]

Or, without lambda...

def cf(t):
    a, b = t
    return -b, a

print(sorted(tlist, key=cf))
DarkKnight
  • 19,739
  • 3
  • 6
  • 22