Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按两个元素对嵌套列表排序_Python_List_Sorting - Fatal编程技术网

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
,您最终得到了所需的排序顺序