Jonas
Jonas

Reputation: 454

How to sort a list in descending order for the first criteria and ascending order for the second criteria?

I know that you can sort a list using multiple criterias with the sort or sorted functions, like this:

list = sorted(list, key=lambda x:(x[0], x[1]))

The code above sorts the list in ascending order and only if the first parameter is equal to another element, the list is sorted in an ascending order following the second criteria.

If you include the parameter reverse=True, it will do the same as I said above, but the list will be sorted in an descending order in both criterias.

That's not what I want though. I'd like to sort the list in an descending order and if there are equal elements, then the tuple will be sorted in an ascending order by the second element.

For example, this code:

list = [(99, 41), (85, 33), (99, 28)]
list = sorted(list, key=lambda x:(x[0], x[1]), reverse=True)
print(list)

prints [(99, 41), (99, 28), (85, 33)] but I want to be printed: [(99, 28), (99, 41), (85, 33)]

Upvotes: 0

Views: 785

Answers (2)

Daniel Hao
Daniel Hao

Reputation: 4980

Try this way, maybe that helps:

It works because your items are tuples so we use the tricks to sort them by desc/asceding order differently. So the first will be descending order, and 2nd ascending as it shown.

Notes - please don't use Python built-in as the variable names.

>>> L =  [(99, 41), (85, 33), (99, 28)]
>>> sorted(L, key=lambda x: (-x[0], x[1]))
[(99, 28), (99, 41), (85, 33)]

>>> A = [(12, 22), (13, 33), (12, 12), (13, 3)]
>>> A.sort(key=lambda x: (-x[0], x[1]))      # in-place sort
>>> 
>>> A
[(13, 3), (13, 33), (12, 12), (12, 22)]

Upvotes: 0

Yazmin Melgoza
Yazmin Melgoza

Reputation: 41

>>> new_list = sorted(list, key=lambda x:(x[0], 1/x[1]), reverse=True)
>>> print(new_list)
[(99, 28), (99, 41), (85, 33)]

This lambda function orders in ascending order but not based on x[0] and x[1], but in x[0] and 1/x[1]

1/x[1] is simply the inverse of x[1] which will be smaller as x[1] gets bigger

For example:

  • 1/28 = 0.03571
  • 1/33 = 0.03030
  • 1/48 = 0.02083

Upvotes: 0

Related Questions