【Python】多维列表排序

单键排序

按升序排序

按第 0 个元素升序排序。

score = [[80, 65], [77, 45], [10, 99], [100, 100], [85, 43]]
score = sorted(score, key=lambda x: x[0])
print(score)
>> [[10, 99], [77, 45], [80, 65], [85, 43], [100, 100]]

按降序排列

按第 0 个元素降序排序。

score = [[80, 65], [77, 45], [10, 99], [100, 100], [85, 43]]
score = sorted(score, key=lambda x: x[0], reverse=True)
print(score)
>> [[100, 100], [85, 43], [80, 65], [77, 45], [10, 99]]

按多个键排序

按升序排序

按第 0 个和第 2 个元素升序排序。

score = [[80, 65, 75], [77, 45, 95], [77, 99, 65], [100, 100, 0], [85, 43, 20]]
score = sorted(score, key=lambda x: (x[0], x[2]))
print(score)
>> [[77, 99, 65], [77, 45, 95], [80, 65, 75], [85, 43, 20], [100, 100, 0]]

按升序和降序排序

按升序对第 0 个元素进行排序,按降序对第 2 个元素进行排序。
如果使用反向,所有关键元素都将按降序排列,因此将 - 添加到您想要按降序排列的元素中。

score = [[80, 65, 75], [77, 45, 95], [77, 99, 65], [100, 100, 0], [85, 43, 20]]
score = sorted(score, key=lambda x: (x[0], -x[2]))
print(score)
>> [[77, 45, 95], [77, 99, 65], [80, 65, 75], [85, 43, 20], [100, 100, 0]]

(很难找到一篇关于如何按升序对一个元素进行排序并按降序对另一个元素进行排序的文章。)

相关推荐

  1. Python列表排序

    2023-12-15 16:56:02       60 阅读
  2. Python】案例:列表拆分和去重

    2023-12-15 16:56:02       47 阅读
  3. Python列表排序

    2023-12-15 16:56:02       36 阅读
  4. Python 中字符串列表排序

    2023-12-15 16:56:02       36 阅读
  5. Python入门与进阶】Python列表进行排序

    2023-12-15 16:56:02       33 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-15 16:56:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-15 16:56:02       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-15 16:56:02       82 阅读
  4. Python语言-面向对象

    2023-12-15 16:56:02       91 阅读

热门阅读

  1. 46.0/基本的 HTML 标签(详细版)

    2023-12-15 16:56:02       59 阅读
  2. Electron 打开开发者工具 devtools

    2023-12-15 16:56:02       67 阅读
  3. LeetCode 2454. 下一个更大元素 IV

    2023-12-15 16:56:02       63 阅读
  4. pip 通过git安装库

    2023-12-15 16:56:02       46 阅读