python - 按两个元素对嵌套列表进行排序

标签 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'], ['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) ,您最终会得到所需的排序顺序。

关于python - 按两个元素对嵌套列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34705205/

相关文章:

c++ - 根据类内的字符串对用户定义类的 vector 进行排序

python - 提取 numpy 3D 数组

python - django 1.5 select_for_update 被认为是脆弱的设计

python - 在 Python 中导入 tensorflow 时出现非法指令

r - 如何过滤R中的列表

python - 存储一对需要在 Python 中经常更新的值的最佳方法?

python - SQLAlchemy:如何扩展混合属性?

python - 对映射中的键进行排序

python - 按推送顺序存储 Python 字典条目

javascript - 忽略空白值对 json 进行排序