5

There is a class with two domains of value. I want sort a list of such pairs with following criteria:

  1. If the first domain are different, sort by first domain;
  2. Otherwise, sort by second domain.

It is easy to sort only by first domain with lambda:

list.sort(key=lambda x:x.first)

or

sorted(list, key=lambda x:x.first)

But if I want to further compare x.second, how can I write lambda the function?

2
  • 1
    How many different versions of python are you using? Commented Sep 20, 2016 at 0:43
  • what are the type of values in first and second?
    – Mehdi
    Commented Sep 20, 2016 at 0:44

1 Answer 1

5

Map them to tuples!

sorted(list, key=lambda x:(x.first, x.second))

Tuple comparison happens in the same way you want -- Compare the first element of both tuples, if they are same, move on and decide outcome based on comparison of second element.

PS1: I am assuming x.first and x.second can be compared. (either types such as integers/string, or objects with __eq__ defined.

PS2: I'd suggest implementing __lt__(..) on the x's class. That way you wont have to pass in a lambda for the call to sort.