-3

So let's assume that we have this list:

data=[[A, 5, 200], [B, 5, 220], [C, 4, 150], [D, 4, 150], [E, 1, 50]]

and we want to sort it with the first number (increasing order) and in case of a tie, the second number (decreasing order), and in case of a tie again, in alphabetical order. I tried this code but it just didn't work:

data = sorted(data, key = operator.itemgetter(1, 2))

Is there a better way of doing this ?

Hamid
  • 3
  • 2

1 Answers1

1

In general, you need a key function that is easier to define using functools.cmp_to_key:

# Quick and dirty definition of cmp for Python 3
def cmp(a, b):
    """Return 0 if a == b, negative if a < b, and positive if a > b"""
    return (a > b) - (a < b)

def compare(a, b):
    return (cmp(a[1], b[1]) 
            or cmp(b[2], a[2])  # swap arguments for reversed ordering
            or cmp(a[0], b[0]))

sorted(data, key=functools.cmp_to_key(compare))

However, you can take advantage of the fact that for numbers, a < b implies -a > -b, to write

sorted(data, key=lambda a: (a[1], -a[2], a[0]))
chepner
  • 497,756
  • 71
  • 530
  • 681