0

To sort a tuple list using two columns I do:

t_l = sorted(t_l, key = lambda t_l: (t_l[-1], t_l[1]))

How can I sort such that t_l[-1] is in ascending order, which is the default, but t_l[1] is sorted in descending order?

Using reverse = True would sort both columns in descending order.

Any ideas?

PythonRunner
  • 1,531
  • 2
  • 12
  • 11

2 Answers2

0

You can reverse the sort of one of the columns if either of the columns is numeric, or can be expressed as numbers as well. You can then simply negate the numeric column to reverse the sort for that column.

If the t_l[-1] column is numeric, use:

sorted(t_l, key=lambda i: (-i[-1], i[1]))

(using different names for the input list and the lambda argument reduces confusion)

If that column is not numeric but the other one is, you can still use the same trick, but need to reverse the whole sort:

sorted(t_l, key=lambda i: (i[-1], -i[1]), reverse=True)

Single-character columns can be made numeric by using the ord() function; using ord() will result in the same sorting order, but since it is numeric you can now reverse it:

sorted(t_l, key=lambda i: (-ord(i[-1]), i[1]))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

I tried out a simple solution on an example

t_l = [[3,4,5,6,2,4,6],[6,7,3,4,5]]

t_l = [sorted(t_l[0], reverse = False),sorted(t_l[1], reverse = True)] 

gives

>>> t_l
[[2, 3, 4, 4, 5, 6, 6], [7, 6, 5, 4, 3]]

is it what you look for?

kiriloff
  • 25,609
  • 37
  • 148
  • 229