“按x(升序),然后按y(降序)为csv文件在python [英] "sort by x (ascending) then by y (descending)" for a csv file in python
问题描述
所以我有一个csv文件,我想使用2列排序(基本上相同的想法在excel中的按顺序由somecol然后由anothercol)。
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").
鉴于csvbody是从csv文件生成的列表的列表,我现在的方式,我发现从这个问题是 sortedcsv = sorted(csvbody,key = operator.itemgetter(somecol,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)?
我知道我可以做 sortedcsv = sorted(csvbody,key = operator.itemgetter(somecol,anothercol),reverse = True)
但是它会按降序对它们进行排序。然后我尝试做两行:
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))
这不工作,因为第二次排序只是覆盖第一次排序(就好像我进入excel,并按降序排序只是由anothercol)
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.
推荐答案
由于Python的排序是保证稳定,需要:
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))
参考:
- https://wiki.python.org/moin/HowTo/Sorting#Sort_Stability_and_Complex_Sorts
这篇关于“按x(升序),然后按y(降序)为csv文件在python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!