在Python中对CSV文件进行“按x(升序)排序然后按y(降序)排序”

1 投票
1 回答
1426 浏览
提问于 2025-04-18 18:31

我有一个CSV文件,想用两个列来排序(就像在Excel里选择“先按某列排序,再按另一列排序”一样)。

现在,csvbody是从CSV文件生成的一个列表的列表。我找到的排序方法是 sortedcsv = sorted(csvbody, key = operator.itemgetter(somecol, anothercol))。问题是我想要按somecol升序排序,而按anothercol降序排序。有没有办法做到这一点(最好能用一行代码)?

我知道我可以用 sortedcsv = sorted(csvbody, key = operator.itemgetter(somecol, anothercol), reverse = True),但这样会把两个列都按降序排序。然后我尝试用两行代码:

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

但是这样不行,因为第二次排序会覆盖第一次排序(就像我在Excel里只按“anothercol”降序排序一样)。

如果你需要我提供更多信息,请告诉我。

1 个回答

2

因为Python的排序是保证稳定的,所以这样做应该能满足你的需求:

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

参考资料:

撰写回答