“按x(升序),然后按y(降序)”为python中的csv文件

所以我有一个csv文件,我想要使用2列(基本上相同的想法在Excelsorting“由somecol然后anothercol”)。

鉴于csvbody是从csv文件生成的列表的列表,我现在的方式,我发现这个问题 sortedcsv = sorted(csvbody, key = operator.itemgetter(somecol, anothercol))问题是,我想要按照升序sorting,而按降序sorting。 有没有办法做到这一点(甚至更好,在一条线)?

我知道我可以做sortedcsv = sorted(csvbody, key = operator.itemgetter(somecol, anothercol), reverse = True) ,然后按降序对它们进行sorting。 然后我试着做两行:

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

然而,这是行不通的,因为第二类只是覆盖第一类(就好像我进入了Excel,并按“anothercol”降序排列)

如果你需要我包括更多的信息,请让我知道。

由于Python的sorting是保证稳定的,这应该做你想要的:

 # 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)) 

参考: