sorted函数
一、sorted() 函数
1. 是什么
sorted() 是 Python 的内置函数,作用是返回一个新的已排序列表,不会改动原来的可迭代对象。这一点和列表方法 list.sort() 不同——后者是原地排序、返回 None,且只能用于列表。
nums = [3, 1, 4, 1, 5]
new_nums = sorted(nums)
print(new_nums) # [1, 1, 3, 4, 5]
print(nums) # [3, 1, 4, 1, 5] 原列表不变
2. 函数签名
sorted(iterable, *, key=None, reverse=False)
- iterable:任何可迭代对象(列表、元组、字符串、字典、集合、生成器等)。
- key:一个函数,接收单个元素并返回用于比较的“排序依据”,默认用元素本身。
- reverse:为
True时降序,默认False升序。
注意 key 和 reverse 是仅限关键字参数,必须写成 key=...、reverse=...,不能按位置传。
3. 常见用法
3.1 基本排序
sorted("python") # ['h', 'n', 'o', 'p', 't', 'y']
sorted({3, 1, 2}) # [1, 2, 3]
sorted((5, 2, 8)) # [2, 5, 8]
3.2 用 key 指定排序依据
words = ["banana", "apple", "cherry"]
sorted(words, key=len) # ['apple', 'banana', 'cherry']
# 忽略大小写
sorted(words, key=str.lower)
# 按字典的 value 排序
scores = {"Tom": 88, "Amy": 95, "Bob": 72}
sorted(scores.items(), key=lambda x: x[1], reverse=True)
# [('Amy', 95), ('Tom', 88), ('Bob', 72)]
3.3 多条件排序
key 返回元组即可,按元组元素依次比较:
students = [("Amy", 18), ("Bob", 20), ("Tom", 18)]
sorted(students, key=lambda s: (s[1], s[0]))
# [('Amy', 18), ('Tom', 18), ('Bob', 20)]
若某个条件要降序、其他升序,可对数值取负,或用 reverse=True 配合次级条件反转。
3.4 稳定排序
Python 的排序(Timsort)是稳定的:值相等的元素保持原有相对顺序。因此可以“先排次要条件,再排主要条件”:
data = [("b", 1), ("a", 2), ("c", 1)]
step1 = sorted(data, key=lambda x: x[0]) # 先按字母
step2 = sorted(step1, key=lambda x: x[1]) # 再按数字,同组内字母序保留
3.5 自定义比较(不推荐常用)
functools.cmp_to_key 可以把旧式比较函数转成 key:
from functools import cmp_to_key
sorted(nums, key=cmp_to_key(lambda a, b: b - a)) # 降序
4. 与 list.sort() 的对比
| 对比项 | sorted(iterable) |
lst.sort() |
|---|---|---|
| 返回值 | 新列表 | None |
| 是否修改原对象 | 否 | 是(原地) |
| 支持的类型 | 任意可迭代对象 | 仅列表 |
| 参数 | key、reverse 为关键字参数 |
同样支持 key、reverse |
| 适用场景 | 需要保留原数据、或对非列表排序 | 数据量大且不需要原顺序,省内存 |
5. 几个易踩的坑
- 对字典排序:
sorted(d)只排键;要排值需用d.items()配合key。 - 混合类型会报错:
sorted([1, "a"])抛TypeError,因为int和str不能比较,此时必须给key。 key对每个元素只调用一次(装饰-排序-去装饰),所以 key 函数里做昂贵计算比在比较函数里做要高效得多。- 字符串排序按 Unicode 码点:
sorted(["B", "a", "A"])得到['A', 'B', 'a'],需要忽略大小写时记得key=str.lower。 - 中文排序默认按 Unicode 编码,不是拼音序;需要拼音序可借助
pypinyin等库作为 key。 - 不要写
lst = lst.sort(),这会把变量变成None。