Python 按两个元素对嵌套列表排序
假设我有一个如下列表:Python 按两个元素对嵌套列表排序,python,list,sorting,Python,List,Sorting,假设我有一个如下列表: [['Harry', '4'], ['Anthony', '10'], ['Adam', '7'], ['Joe', '6'], ['Ben', '10']] # we can say the first element in it's lists is `name`, the second is `score` 我想把它分类为: [['Anthony', '10'], ['Ben', '10'], ['Adam', '7'], ['Joe', '6'], ['Harr
[['Harry', '4'], ['Anthony', '10'], ['Adam', '7'], ['Joe', '6'], ['Ben', '10']]
# we can say the first element in it's lists is `name`, the second is `score`
我想把它分类为:
[['Anthony', '10'], ['Ben', '10'], ['Adam', '7'], ['Joe', '6'], ['Harry', '4']]
因此,首先按分数降序排序,然后按名称升序排序
我试过:
>>> sorted(l, key=lambda x: (int(x[1]), x[0]))
[['Harry', '4'], ['Joe', '6'], ['Adam', '7'], ['Anthony', '10'], ['Ben', '10']]
它正在工作,所以现在我只需要反转它:
>>> sorted(l, key=lambda x: (int(x[1]), x[0]), reverse=True)
[['Ben', '10'], ['Anthony', '10'], ['Adam', '7'], ['Joe', '6'], ['Harry', '4']]
啊,reverse=True
只是简单地反转了列表,但没有给出预期的输出。所以我只想反转int(x[1])
,而不是x[0]
我该怎么做
>>> sorted(l, key=lambda x: (-int(x[1]), x[0]))
[['Anthony', '10'], ['Ben', '10'], ['Adam', '7'], ['Joe', '6'], ['Harry', '4']]
基本上,通过更改键的分数部分的符号,排序键将为:
(-10, 'Anthony'),
(-10, 'Ben'),
(-7, 'Adam'),
(-6, 'Joe'),
(-4, 'Harry')
因此,使用(a,b)<(c,d)(a
,您最终得到了所需的排序顺序