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.
Since Python's sort is guaranteed to be stable, this should do what you want:
Reference: