【发布时间】:2016-01-10 12:12:07
【问题描述】:
假设我有一个如下列表:
[['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]。
我该怎么做?
【问题讨论】: