Python高级特性:sorted() 排序完全指南
灵活、高效的数据排序
前言
排序是编程中最常用的操作之一。Python 提供了内置的 sorted() 函数,可以对各种可迭代对象进行排序。与列表的 sort() 方法不同,sorted() 会返回一个新列表,原对象保持不变。
本文将系统讲解 sorted() 的基本用法、自定义排序规则、复杂对象排序、多级排序以及性能优化技巧,帮助你掌握Python中强大的排序功能。
📚 本文内容基于:道满PythonAI - 排序教程
一、排序基础
1.1 基本语法
sorted(iterable, key=None, reverse=False)
| 参数 | 说明 |
|---|---|
iterable |
可迭代对象(列表、元组、字符串等) |
key |
可选,指定排序依据的函数 |
reverse |
可选,True为降序,False为升序(默认) |
| 返回值 | 新的排序后的列表 |
1.2 基本示例
# 数字排序
numbers = [36, 5, -12, 9, -21]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [-21, -12, 5, 9, 36]
print(numbers) # [36, 5, -12, 9, -21] 原列表不变
# 字符串排序(按ASCII码)
words = ['banana', 'apple', 'Cherry', 'date']
print(sorted(words)) # ['Cherry', 'apple', 'banana', 'date']
# 注意:大写字母排在小写字母前面(ASCII码中'A'=65, 'a'=97)
二、自定义排序:key 参数
sorted() 是一个高阶函数,可以接收 key 参数来自定义排序规则。key 函数会应用于每个元素,然后根据返回的结果进行排序。
2.1 按绝对值排序
numbers = [36, 5, -12, 9, -21]
# 按绝对值排序
sorted_by_abs = sorted(numbers, key=abs)
print(sorted_by_abs) # [5, 9, -12, -21, 36]
# 计算过程:
# abs(36)=36, abs(5)=5, abs(-12)=12, abs(9)=9, abs(-21)=21
# 按[36,5,12,9,21]排序 → [5,9,12,21,36]
# 对应原值 → [5, 9, -12, -21, 36]
2.2 按字符串长度排序
words = ['python', 'is', 'awesome', 'and', 'powerful']
# 按长度升序
sorted_by_len = sorted(words, key=len)
print(sorted_by_len)
# ['is', 'and', 'python', 'awesome', 'powerful']
# 按长度降序
sorted_by_len_desc = sorted(words, key=len, reverse=True)
print(sorted_by_len_desc)
# ['awesome', 'powerful', 'python', 'and', 'is']
三、字符串排序与大小写处理
3.1 默认ASCII排序的问题
words = ['bob', 'about', 'Zoo', 'Credit']
# 默认排序(按ASCII码)
print(sorted(words))
# ['Credit', 'Zoo', 'about', 'bob']
# 因为 'C' (67) < 'Z' (90) < 'a' (97) < 'b' (98)
3.2 忽略大小写排序
使用 str.lower 或 str.upper 作为 key 函数:
words = ['bob', 'about', 'Zoo', 'Credit']
# 忽略大小写排序
sorted_ignore_case = sorted(words, key=str.lower)
print(sorted_ignore_case)
# ['about', 'bob', 'Credit', 'Zoo']
# 降序
sorted_desc = sorted(words, key=str.lower, reverse=True)
print(sorted_desc)
# ['Zoo', 'Credit', 'bob', 'about']
四、复杂对象排序
4.1 对元组列表排序
students = [('Bob',

3132

被折叠的 条评论
为什么被折叠?



