当前位置:首页 > Python > 正文

掌握Python排序利器(sorted函数从入门到精通)

在日常编程中,对数据进行排序是一项非常常见的操作。Python 提供了强大而灵活的 sorted 函数,可以帮助我们轻松实现各种排序需求。无论你是刚接触编程的新手,还是有一定经验的开发者,掌握 Python sorted函数 都能极大提升你的编码效率。

掌握Python排序利器(sorted函数从入门到精通) Python sorted函数  sorted排序方法 Python列表排序 sorted函数教程 第1张

什么是 sorted 函数?

sorted() 是 Python 内置的一个函数,用于对可迭代对象(如列表、元组、字符串等)进行排序,并返回一个新的已排序的列表。它不会修改原始数据,而是生成一个副本。

这与列表的 .sort() 方法不同——.sort() 是原地排序,会直接修改原列表。

基本用法示例

最简单的用法是对数字列表或字符串列表进行升序排序:

# 对数字列表排序numbers = [3, 1, 4, 1, 5, 9]sorted_numbers = sorted(numbers)print(sorted_numbers)  # 输出: [1, 1, 3, 4, 5, 9]# 对字符串列表排序words = ['banana', 'apple', 'cherry']sorted_words = sorted(words)print(sorted_words)  # 输出: ['apple', 'banana', 'cherry']

注意:原始的 numberswords 列表没有被改变!

降序排序

只需设置参数 reverse=True 即可实现降序排序:

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

使用 key 参数自定义排序规则

这是 sorted函数 最强大的功能之一!通过 key 参数,你可以指定一个函数来决定排序依据。

例如,按字符串长度排序:

words = ['python', 'is', 'awesome']sorted_by_len = sorted(words, key=len)print(sorted_by_len)  # 输出: ['is', 'python', 'awesome']

再比如,对包含字典的列表按某个字段排序:

students = [    {'name': 'Alice', 'score': 88},    {'name': 'Bob', 'score': 95},    {'name': 'Charlie', 'score': 76}]# 按分数升序排序sorted_students = sorted(students, key=lambda x: x['score'])print(sorted_students)# 输出: [{'name': 'Charlie', 'score': 76}, {'name': 'Alice', 'score': 88}, {'name': 'Bob', 'score': 95}]

常见应用场景

  • 对日志时间戳排序
  • 按用户评分对商品排序
  • 对文件名按数字部分排序(需配合正则)
  • 多级排序(先按年龄,再按姓名)

多级排序可以通过返回元组的 key 函数实现:

people = [    ('Alice', 30),    ('Bob', 25),    ('Alice', 25)]# 先按名字,再按年龄排序sorted_people = sorted(people, key=lambda x: (x[0], x[1]))print(sorted_people)# 输出: [('Alice', 25), ('Alice', 30), ('Bob', 25)]

小结

通过本教程,你已经掌握了 Python sorted函数 的核心用法:基本排序、降序、自定义排序规则以及多级排序。这些技巧不仅能帮你高效处理 Python列表排序 任务,还能应用于更复杂的数据结构。

记住:sorted() 返回新列表,安全且灵活;而 .sort() 修改原列表,节省内存。根据实际需求选择即可。

希望这篇 sorted函数教程 能助你在 Python 编程之路上更进一步!