“sort by x (ascending) then by y (descending)” for

2019-08-13 23:07发布

So I have a csv file that I want to sort using 2 columns (basically the same idea in excel as "sort by somecol then by anothercol").

Given that csvbody is a list of lists generated from the csv file, the way I have it right now that I found from this question is sortedcsv = sorted(csvbody, key = operator.itemgetter(somecol, anothercol)) The issue is that I want to sort by somecol in ascending order and anothercol in descending order. Is there a way to do this (even better, in one line)?

I know that I could do sortedcsv = sorted(csvbody, key = operator.itemgetter(somecol, anothercol), reverse = True) but then it sorts both of them in descending order. Then I tried doing two lines:

sort1 = sorted(csvbody, key = operator.itemgetter(somecol))
sort2 = sorted(sort1, key = operator.itemgetter(anothercol), reverse = True))

However this doesn't work because the second sort just overrides the first sort (it's as if I went into excel and sorted in descending order just by "anothercol")

If you need me to include more information please let me know.

1条回答
在下西门庆
2楼-- · 2019-08-13 23:59

Since Python's sort is guaranteed to be stable, this should do what you want:

# First sort by secondary key
sortedcsv = sorted(csvbody, key=operator.itemgetter(anothercol, reverse=True)
# Then sort by primary key
sortedcsv = sorted(sortedcsv, key=operator.itemgetter(somecol))

Reference:

查看更多
登录 后发表回答