接下来我们详细解析 Python 中超级重大的内置函数 sorted()
1. 函数定义
sorted() 函数用于对任何可迭代对象进行排序,并返回一个新的排序后的列表。
- 语法:sorted(iterable, *, key=None, reverse=False)
- 参数:
- iterable:必需,要排序的可迭代对象(列表、元组、字符串、字典等)
- key:可选,指定排序规则的函数
- reverse:可选,布尔值,True 表明降序,False 表明升序(默认)
- 返回值:一个新的排序后的列表(不会修改原始对象)
2. 基本用法示例
数字排序
# 数字列表排序
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出: [1, 1, 2, 3, 4, 5, 9]
print(numbers) # 输出: [3, 1, 4, 1, 5, 9, 2] (原列表不变)
# 降序排序
print(sorted(numbers, reverse=True)) # 输出: [9, 5, 4, 3, 2, 1, 1]
字符串排序
# 字符串列表按字母顺序排序
fruits = ['banana', 'apple', 'cherry', 'date']
print(sorted(fruits)) # 输出: ['apple', 'banana', 'cherry', 'date']
# 字符串本身排序(按字符ASCII码)
text = "python"
print(sorted(text)) # 输出: ['h', 'n', 'o', 'p', 't', 'y']
print(''.join(sorted(text))) # 输出: 'hnopty'
不同类型的数据结构
# 元组排序(返回列表)
tuple_data = (5, 2, 8, 1)
print(sorted(tuple_data)) # 输出: [1, 2, 5, 8]
# 集合排序(返回列表)
set_data = {3, 1, 4, 1, 5}
print(sorted(set_data)) # 输出: [1, 3, 4, 5]
# 字典排序(默认按键排序)
dict_data = {'c': 3, 'a': 1, 'b': 2}
print(sorted(dict_data)) # 输出: ['a', 'b', 'c']
print(sorted(dict_data.items())) # 输出: [('a', 1), ('b', 2), ('c', 3)]
3. 高级用法:key参数
key 参数是 sorted() 函数最强劲的功能,它允许你自定义排序规则。
按字符串长度排序
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
# 按字母顺序(默认)
print(sorted(words)) # 输出: ['apple', 'banana', 'cherry', 'date', 'elderberry']
# 按字符串长度排序
print(sorted(words, key=len)) # 输出: ['date', 'apple', 'banana', 'cherry', 'elderberry']
按字典的值排序
students = [
{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 92},
{'name': 'Charlie', 'score': 78}
]
# 按分数排序
print(sorted(students, key=lambda x: x['score']))
# 输出: [{'name': 'Charlie', 'score': 78}, {'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}]
# 按分数降序排序
print(sorted(students, key=lambda x: x['score'], reverse=True))
# 输出: [{'name': 'Bob', 'score': 92}, {'name': 'Alice', 'score': 85}, {'name': 'Charlie', 'score': 78}]
多级排序
# 先按长度排序,长度一样的按字母顺序
words = ['apple', 'banana', 'cherry', 'date', 'fig']
print(sorted(words, key=lambda x: (len(x), x)))
# 输出: ['fig', 'date', 'apple', 'banana', 'cherry']
# 先按分数降序,分数一样的按姓名升序
students = [
{'name': 'Alice', 'score': 85},
{'name': 'Bob', 'score': 92},
{'name': 'Charlie', 'score': 85},
{'name': 'David', 'score': 78}
]
print(sorted(students, key=lambda x: (-x['score'], x['name'])))
# 输出: [{'name': 'Bob', 'score': 92}, {'name': 'Alice', 'score': 85}, {'name': 'Charlie', 'score': 85}, {'name': 'David', 'score': 78}]
使用内置函数作为 key
# 忽略大小写排序
words = ['Apple', 'banana', 'CHERRY', 'date']
print(sorted(words, key=str.lower)) # 输出: ['Apple', 'banana', 'CHERRY', 'date']
# 按绝对值排序
numbers = [-5, 3, -1, 4, -2]
print(sorted(numbers, key=abs)) # 输出: [-1, -2, 3, 4, -5]
4. 与list.sort()方法的区别
这是一个超级重大的区别:
|
特性 |
sorted() |
list.sort() |
|
返回值 |
返回新列表 |
返回 None(原地修改) |
|
原始对象 |
不修改原对象 |
修改原列表 |
|
适用性 |
任何可迭代对象 |
仅列表对象 |
|
链式操作 |
支持 |
不支持 |
numbers = [3, 1, 4, 2]
# sorted() 用法
result = sorted(numbers)
print(result) # 输出: [1, 2, 3, 4]
print(numbers) # 输出: [3, 1, 4, 2] (原列表不变)
# list.sort() 用法
numbers.sort()
print(numbers) # 输出: [1, 2, 3, 4] (原列表被修改)
5. 复杂对象排序
自定义类对象排序
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person({self.name}, {self.age})"
people = [
Person("Alice", 25),
Person("Bob", 30),
Person("Charlie", 20)
]
# 按年龄排序
print(sorted(people, key=lambda p: p.age))
# 输出: [Person(Charlie, 20), Person(Alice, 25), Person(Bob, 30)]
# 按姓名排序
print(sorted(people, key=lambda p: p.name))
# 输出: [Person(Alice, 25), Person(Bob, 30), Person(Charlie, 20)]
使用operator模块
import operator
people = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30},
{'name': 'Charlie', 'age': 20}
]
# 使用 operator.itemgetter
print(sorted(people, key=operator.itemgetter('age')))
# 输出: [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
# 使用 operator.attrgetter(对于自定义对象)
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __repr__(self):
return f"Product({self.name}, ${self.price})"
products = [Product("Laptop", 1000), Product("Mouse", 25), Product("Keyboard", 75)]
print(sorted(products, key=operator.attrgetter('price')))
# 输出: [Product(Mouse, $25), Product(Keyboard, $75), Product(Laptop, $1000)]
6. 性能思考和最佳实践
- 稳定性:sorted() 是稳定排序,相等元素的相对顺序保持不变
- 时间复杂度:使用 Timsort 算法,平均和最坏情况都是 O(n log n)
- 内存使用:返回新列表,需要额外内存空间
# 对于大数据集,思考使用生成器表达式
large_data = (x for x in range(1000000)) # 生成器
sorted_data = sorted(large_data) # 依旧需要将所有数据加载到内存
# 如果内存是瓶颈,思考其他方法(如分批处理)
7. 实际应用场景
场景1:数据处理和分析
# 从CSV数据中提取并排序
data = [
('Alice', 'Engineering', 50000),
('Bob', 'Marketing', 45000),
('Charlie', 'Engineering', 55000),
('David', 'Sales', 40000)
]
# 按薪资降序排序
sorted_by_salary = sorted(data, key=lambda x: x[2], reverse=True)
print(sorted_by_salary)
# 输出: [('Charlie', 'Engineering', 55000), ('Alice', 'Engineering', 50000), ('Bob', 'Marketing', 45000), ('David', 'Sales', 40000)]
场景2:文件处理
# 按文件大小排序文件
import os
files = ['file1.txt', 'file2.txt', 'file3.txt']
# 假设这些文件存在并有不同大小
sorted_files = sorted(files, key=lambda f: os.path.getsize(f))
print(sorted_files)
8. 注意事项
- 类型一致性:排序的元素必须是可比较的
# mixed = [1, 'a', 2] # TypeError: '<' not supported between instances of 'str' and 'int'
# sorted(mixed)
- 自定义排序函数:对于复杂排序,key 函数应该返回可比较的类型
- 内存思考:对于超级大的数据集,sorted() 可能不是最佳选择
总结
|
特性 |
描述 |
|
功能 |
对可迭代对象进行排序,返回新列表 |
|
参数 |
iterable, key, reverse |
|
返回值 |
新的排序后的列表 |
|
关键特性 |
稳定排序、不修改原对象、支持自定义排序规则 |
|
时间复杂度 |
O(n log n) |
|
适用场景 |
数据排序、数据分析、文件处理等 |
sorted() 是 Python 中最常用和强劲的函数之一,它的灵活性和强劲的 key 参数使其能够处理各种复杂的排序需求。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
收藏了,感谢分享