假设我有一个如下列表:
[['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 < c) or (a == c and b < d)
您最终得到了所需的排序顺序.