Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Ascending Descending for each column when sorting by multiple columns [duplicate]

I have a list d that I wish to sort. I sort by the first column first. If its a tie there I then go on to use the second column to sort. Say I want to sort by the first column in ascending order but sort by the second column in descending order. Ascending being the default, using the reverse key I thought the below should work.

sorted(d,key=lambda x: (x[0],x[1]),reverse=(False,True))

But it does not. It give the following error.

    reverse=(False,True))

TypeError: an integer is required (got type tuple)

So if I'm not doing it right how to fix it? Or the way to do this is completely different? Advice on that would be helpful.

My question indeed has some duplication but there are already interesting responses, so I would like to keep it.

like image 512
ztyh Avatar asked Sep 18 '25 06:09

ztyh


2 Answers

(Might be overkill, but..) Using pandas and args ascending=[True, False]:

d = [[1,2], [2,2], [2,3], [2,4], [3,1]]
df=  pd.DataFrame(d)

sorted_values = df.sort_values(by=[0,1], ascending=[True,False])
sorted_list = sorted_values.agg(list,1).tolist()

[[1, 2], [2, 4], [2, 3], [2, 2], [3, 1]]
like image 182
rafaelc Avatar answered Sep 19 '25 22:09

rafaelc


From the docs:

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

So what you want instead is something like:

d.sort(key=lambda x: (x[0], -x[1]))

If x[1] is not a number, try:

d.sort(key=lambda x: x[1], reverse=True)
d.sort(key=lambda x: x[0])
like image 24
minmax Avatar answered Sep 19 '25 20:09

minmax