<分区>
假设我有如下列表:
[['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]
。
我该怎么做?