从基础到进阶详解Python如何根据列表中某字段排序

 更新时间:2026年03月29日 09:36:20   作者:detayun  
在 Python 开发中,我们经常需要对列表(List)中的元素进行排序,本文将详细介绍 Python 中如何根据列表中某字段排序,文中的示例代码讲解详细,有需要的小伙伴可以参考下

在 Python 开发中,我们经常需要对列表(List)中的元素进行排序。如果列表中的元素是简单的数字或字符串,可以直接使用 sorted()list.sort() 方法。但如果列表中的元素是字典(dict)或自定义对象(class),并且需要根据某个字段(key)进行排序,该怎么办呢?

本文将详细介绍 Python 中如何根据列表中某字段排序,涵盖 字典列表排序自定义对象排序 以及 高级排序技巧(如多字段排序、降序排序等)。

1. 基础排序:数字和字符串列表

如果列表中的元素是数字或字符串,可以直接使用 sorted()list.sort()

numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)  # 升序
print(sorted_numbers)  # [1, 1, 2, 3, 4, 5, 9]

numbers.sort(reverse=True)  # 降序(原地修改)
print(numbers)  # [9, 5, 4, 3, 2, 1, 1]

字符串排序:

words = ["banana", "apple", "cherry", "date"]
sorted_words = sorted(words)
print(sorted_words)  # ['apple', 'banana', 'cherry', 'date']

2. 字典列表排序:根据某个键(key)排序

如果列表中的元素是字典,并且需要根据某个键(如 "age""score")排序,可以使用 sorted()key 参数。

示例 1:根据字典的某个键排序

students = [
    {"name": "Alice", "age": 20, "score": 90},
    {"name": "Bob", "age": 18, "score": 85},
    {"name": "Charlie", "age": 22, "score": 95}
]

# 按 age 升序排序
sorted_by_age = sorted(students, key=lambda x: x["age"])
print(sorted_by_age)
"""
[
    {'name': 'Bob', 'age': 18, 'score': 85},
    {'name': 'Alice', 'age': 20, 'score': 90},
    {'name': 'Charlie', 'age': 22, 'score': 95}
]
"""

# 按 score 降序排序
sorted_by_score_desc = sorted(students, key=lambda x: x["score"], reverse=True)
print(sorted_by_score_desc)
"""
[
    {'name': 'Charlie', 'age': 22, 'score': 95},
    {'name': 'Alice', 'age': 20, 'score': 90},
    {'name': 'Bob', 'age': 18, 'score': 85}
]
"""

示例 2:使用operator.itemgetter替代lambda

operator.itemgetter 可以替代 lambda,提高性能(适用于大数据量):

from operator import itemgetter

# 按 name 排序
sorted_by_name = sorted(students, key=itemgetter("name"))
print(sorted_by_name)
"""
[
    {'name': 'Alice', 'age': 20, 'score': 90},
    {'name': 'Bob', 'age': 18, 'score': 85},
    {'name': 'Charlie', 'age': 22, 'score': 95}
]
"""

3. 自定义对象排序:根据属性排序

如果列表中的元素是自定义类的对象,并且需要根据某个属性(如 agescore)排序,可以使用 sorted()key 参数或实现 __lt__ 方法。

示例 1:使用lambda按属性排序

class Student:
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

    def __repr__(self):
        return f"Student(name={self.name}, age={self.age}, score={self.score})"

students = [
    Student("Alice", 20, 90),
    Student("Bob", 18, 85),
    Student("Charlie", 22, 95)
]

# 按 age 排序
sorted_by_age = sorted(students, key=lambda x: x.age)
print(sorted_by_age)
"""
[
    Student(name=Bob, age=18, score=85),
    Student(name=Alice, age=20, score=90),
    Student(name=Charlie, age=22, score=95)
]
"""

示例 2:实现__lt__方法(推荐)

如果经常需要按某个属性排序,可以在类中实现 __lt__(小于)方法,这样可以直接使用 sorted()list.sort()

class Student:
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score

    def __lt__(self, other):
        return self.age < other.age  # 按 age 升序排序

    def __repr__(self):
        return f"Student(name={self.name}, age={self.age}, score={self.score})"

students = [
    Student("Alice", 20, 90),
    Student("Bob", 18, 85),
    Student("Charlie", 22, 95)
]

# 直接排序(无需 key 参数)
sorted_students = sorted(students)
print(sorted_students)
"""
[
    Student(name=Bob, age=18, score=85),
    Student(name=Alice, age=20, score=90),
    Student(name=Charlie, age=22, score=95)
]
"""

如果需要按不同属性排序,可以动态修改 __lt__ 或使用 functools.cmp_to_key(较复杂,不推荐)。

4. 高级排序技巧

多字段排序

如果需要先按 age 排序,再按 score 排序,可以使用 tuple 作为 key

students = [
    {"name": "Alice", "age": 20, "score": 90},
    {"name": "Bob", "age": 18, "score": 85},
    {"name": "Charlie", "age": 20, "score": 95},
    {"name": "David", "age": 18, "score": 80}
]

# 先按 age 升序,再按 score 降序
sorted_students = sorted(
    students,
    key=lambda x: (x["age"], -x["score"])  # 负号实现降序(仅适用于数字)
)
# 或者更通用的方式:
sorted_students = sorted(students, key=lambda x: (x["age"], x["score"]), reverse=False)  # 先 age 升序,再 score 升序
# 如果需要 age 升序,score 降序,可以分两步排序:
students.sort(key=lambda x: x["score"], reverse=True)  # 先按 score 降序
students.sort(key=lambda x: x["age"])  # 再按 age 升序(稳定排序)
print(sorted_students)
"""
[
    {'name': 'David', 'age': 18, 'score': 80},
    {'name': 'Bob', 'age': 18, 'score': 85},
    {'name': 'Alice', 'age': 20, 'score': 90},
    {'name': 'Charlie', 'age': 20, 'score': 95}
]
"""

降序排序

使用 reverse=True 实现降序:

numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_desc = sorted(numbers, reverse=True)
print(sorted_desc)  # [9, 5, 4, 3, 2, 1, 1]

自定义排序逻辑(functools.cmp_to_key)

如果排序逻辑较复杂(如按字符串长度排序),可以使用 functools.cmp_to_key

from functools import cmp_to_key

words = ["banana", "apple", "cherry", "date"]

# 自定义比较函数:按字符串长度排序
def compare(a, b):
    if len(a) < len(b):
        return -1
    elif len(a) > len(b):
        return 1
    else:
        return 0

sorted_words = sorted(words, key=cmp_to_key(compare))
print(sorted_words)  # ['date', 'apple', 'banana', 'cherry']

5. 总结

排序场景方法示例
数字/字符串列表排序sorted() 或 list.sort()sorted([3, 1, 4])
字典列表按某键排序sorted(list, key=lambda x: x["key"])sorted(students, key=lambda x: x["age"])
自定义对象按属性排序sorted(list, key=lambda x: x.attr) 或 __lt__sorted(students, key=lambda x: x.age)
多字段排序sorted(list, key=lambda x: (x["key1"], x["key2"]))sorted(students, key=lambda x: (x["age"], x["score"]))
降序排序reverse=Truesorted(numbers, reverse=True)
复杂排序逻辑functools.cmp_to_keysorted(words, key=cmp_to_key(compare))

推荐做法

  • 优先使用 sorted()(非原地排序)或 list.sort()(原地排序)。
  • 字典列表排序推荐 lambdaoperator.itemgetter
  • 自定义对象排序推荐实现 __lt__ 方法。
  • 多字段排序推荐使用 tuple 作为 key

到此这篇关于从基础到进阶详解Python如何根据列表中某字段排序的文章就介绍到这了,更多相关Python列表排序内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python自动填写问卷星问卷以及提交问卷等功能

    python自动填写问卷星问卷以及提交问卷等功能

    这篇文章主要给大家介绍了关于python自动填写问卷星问卷以及提交问卷等功能的相关资料,包括使用Selenium库模拟浏览器操作、定位元素、填写表单等,通过本文的学习,读者可以了解如何利用Python自动化技术提高问卷填写效率,需要的朋友可以参考下
    2023-03-03
  • pandas DataFrame keys的使用小结

    pandas DataFrame keys的使用小结

    pandas.DataFrame.keys()方法返回DataFrame的列名,类似于字典的键,本文主要介绍了pandas DataFrame keys的使用小结,具有一定的参考价值,感兴趣的可以了解一下
    2025-05-05
  • python生成二维矩阵的两种方法小结

    python生成二维矩阵的两种方法小结

    本文主要介绍了python生成二维矩阵,包含列表生成m行n列的矩阵和numpy生成想要维度的矩阵的两种方法,具有一定的参考价值,感兴趣的可以了解一下
    2024-08-08
  • 利用python爬取散文网的文章实例教程

    利用python爬取散文网的文章实例教程

    这篇文章主要跟大家介绍了利用python爬取散文网文章的相关资料,文中介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2017-06-06
  • Python循环语句中else的用法总结

    Python循环语句中else的用法总结

    这篇文章给大家整理了关于Python中循环语句中else的用法,包括常规的 if else 用法、if else 快捷用法、与 for 关键字一起用、与 while 关键字一起用以及与 try except 一起用的用法总结,有需要的朋友们可以参考借鉴。
    2016-09-09
  • Pycharm无法打开双击没反应的问题及解决方案

    Pycharm无法打开双击没反应的问题及解决方案

    这篇文章主要介绍了Pycharm无法打开,双击没反应,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • 使用Python脚本提取基因组指定位置序列

    使用Python脚本提取基因组指定位置序列

    这篇文章主要为大家介绍了使用Python脚本提取基因组指定位置序列的示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-07-07
  • Python实现账号密码输错三次即锁定功能简单示例

    Python实现账号密码输错三次即锁定功能简单示例

    这篇文章主要介绍了Python实现账号密码输错三次即锁定功能,结合实例形式分析了Python文件读取、流程控制、数据判断等相关操作技巧,需要的朋友可以参考下
    2019-03-03
  • python 如何用 Hypothesis 来自动化单元测试

    python 如何用 Hypothesis 来自动化单元测试

    这篇文章主要介绍了python 如何用 Hypothesis 来自动化单元测试,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-03-03
  • Python字符串拼接的4种方法实例

    Python字符串拼接的4种方法实例

    字符串是所有编程语言中都有的基本变量的类型 ,程序员基本每天都在和字符串打交道,下面这篇文章主要给大家介绍了关于Python字符串拼接的4种方法,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-07-07

最新评论