python中的sorted函数是内置的通用排序工具,能够对列表、元组、字典、集合等所有可迭代对象进行排序,并且不会修改原对象,而是返回一个新的排序后的可迭代对象,使用场景非常广泛。
sorted函数基础语法
sorted函数的基本语法结构如下:
sorted(iterable, key=None, reverse=False)
其中各个参数的含义为:
- iterable:必填参数,表示需要排序的可迭代对象,比如列表、元组等。
- key:可选参数,接收一个函数,这个函数会作用于可迭代对象的每个元素,根据函数返回值进行排序。
- reverse:可选参数,布尔类型,默认值为False表示升序排序,设置为True表示降序排序。
基础使用场景示例
对列表进行排序
对普通数字列表排序是最基础的用法,默认按照升序排列:
# 定义待排序的列表 num_list = [3, 1, 4, 1, 5, 9, 2, 6] # 调用sorted函数排序 sorted_list = sorted(num_list) print(sorted_list) # 输出 [1, 1, 2, 3, 4, 5, 6, 9] print(num_list) # 输出 [3, 1, 4, 1, 5, 9, 2, 6],原列表未被修改
对字符串列表排序
对字符串列表排序时,默认按照字符的ASCII码值升序排列:
str_list = ["apple", "banana", "cherry", "date"] sorted_str = sorted(str_list) print(sorted_str) # 输出 ['apple', 'banana', 'cherry', 'date']
常用实用技巧
使用key参数自定义排序规则
key参数可以接收一个函数,将可迭代对象的每个元素传入该函数,根据函数的返回值进行排序,这是sorted函数最强大的功能之一。
比如我们需要按照字符串的长度对列表进行排序:
str_list = ["apple", "banana", "cherry", "date", "fig"] # 使用len函数作为key,按照字符串长度排序 sorted_by_len = sorted(str_list, key=len) print(sorted_by_len) # 输出 ['fig', 'date', 'apple', 'banana', 'cherry']
再比如对字典列表按照某个键的值排序:
# 学生信息列表,每个元素是包含姓名和分数的字典
student_list = [
{"name": "张三", "score": 85},
{"name": "李四", "score": 92},
{"name": "王五", "score": 78}
]
# 按照score键的值升序排序
sorted_student = sorted(student_list, key=lambda x: x["score"])
print(sorted_student)
# 输出 [{'name': '王五', 'score': 78}, {'name': '张三', 'score': 85}, {'name': '李四', 'score': 92}]
降序排序设置
只需要将reverse参数设置为True,就可以实现降序排序:
num_list = [3, 1, 4, 1, 5, 9, 2, 6] # 降序排序 desc_sorted = sorted(num_list, reverse=True) print(desc_sorted) # 输出 [9, 6, 5, 4, 3, 2, 1, 1]
多条件排序
如果需要按照多个条件排序,可以在key函数中返回一个元组,元组中的元素按照优先级从高到低排列:
# 学生信息列表,先按分数降序,分数相同按姓名升序
student_list = [
{"name": "张三", "score": 85},
{"name": "李四", "score": 92},
{"name": "王五", "score": 85},
{"name": "赵六", "score": 78}
]
# key返回元组,第一个元素是分数取反实现降序,第二个元素是姓名升序
sorted_multi = sorted(student_list, key=lambda x: (-x["score"], x["name"]))
print(sorted_multi)
# 输出 [{'name': '李四', 'score': 92}, {'name': '张三', 'score': 85}, {'name': '王五', 'score': 85}, {'name': '赵六', 'score': 78}]
sorted函数和列表sort方法的区别
很多开发者会混淆sorted函数和列表的sort方法,两者的核心区别如下:
| 对比项 | sorted函数 | 列表sort方法 |
|---|---|---|
| 适用对象 | 所有可迭代对象 | 仅列表对象 |
| 是否修改原对象 | 不修改,返回新对象 | 直接修改原列表,返回None |
| 返回值 | 排序后的新可迭代对象 | 无返回值 |
如果只需要对列表排序且不介意修改原列表,可以使用sort方法,否则优先使用sorted函数,适用性更广。