按多列排序时,为每列设置升序降序 [英] Set Ascending Descending for each column when sorting by multiple columns

查看:202
本文介绍了按多列排序时,为每列设置升序降序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要排序的列表d.我首先按第一列进行排序.如果那是平局,那么我继续使用第二列进行排序.假设我想按升序按第一列排序,但按降序按第二列排序.升为默认值,使用reverse键,我认为以下内容应能工作.

I have a list d that I wish to sort. I sort by the first column first. If its a tie there I then go on to use the second column to sort. Say I want to sort by the first column in ascending order but sort by the second column in descending order. Ascending being the default, using the reverse key I thought the below should work.

sorted(d,key=lambda x: (x[0],x[1]),reverse=(False,True))

但事实并非如此.它给出了以下错误.

But it does not. It give the following error.

    reverse=(False,True))

TypeError: an integer is required (got type tuple)

因此,如果我没有正确执行操作,该如何解决?还是这样做的方式完全不同?对此的建议会有所帮助.

So if I'm not doing it right how to fix it? Or the way to do this is completely different? Advice on that would be helpful.

我的问题确实存在重复,但是已经有有趣的回答,所以我想保留它.

My question indeed has some duplication but there are already interesting responses, so I would like to keep it.

推荐答案

来自 docs :

reverse 是一个布尔值.如果设置为True,则对列表元素进行排序,就好像每个比较都被反转一样.

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

所以您想要的是这样的东西:

So what you want instead is something like:

d.sort(key=lambda x: (x[0], -x[1]))

如果x[1]不是数字,请尝试:

If x[1] is not a number, try:

d.sort(key=lambda x: x[1], reverse=True)
d.sort(key=lambda x: x[0])

这篇关于按多列排序时,为每列设置升序降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆