Python sorted 函数详细介绍 📌 Python 中的 sorted()
函数详解(从入门到高阶)
✅ 1. 什么是 sorted()
? sorted()
是 Python 内置的排序函数 ,可以对任意可迭代对象(如列表、元组、集合、字典等) 进行排序,并返回一个新的有序列表 ,不会修改原始数据 。
🔹 基本语法: 1 sorted (iterable, *, key=None , reverse=False )
参数
说明
iterable
可迭代对象,如list
、tuple
、dict
等
key
排序函数,用于指定排序依据
reverse
是否反向排序,默认为False
(升序)
✅ 2. 基础用法:对列表排序 📌 示例 1:数字升序排序 1 2 3 numbers = [3 , 1 , 4 , 1 , 5 , 9 , 2 ] result = sorted (numbers)print (result)
📌 示例 2:字符串排序(按字母) 1 2 words = ['banana' , 'apple' , 'cherry' ]print (sorted (words))
✅ 注意:原始列表未被修改
✅ 3. 与 .sort()
的区别
特性
sorted()
list.sort()
返回新列表
✅ 是
❌ 否(就地排序)
适用于所有可迭代对象
✅ 是
❌ 仅限list
更推荐在函数式编程中使用
✅ 是
❌ 否
是否破坏原数据
❌ 不破坏
✅ 修改原对象
✅ 4. 使用 reverse=True
实现降序排序 1 2 scores = [60 , 75 , 90 , 88 , 70 ]print (sorted (scores, reverse=True ))
✅ 5. 使用 key
指定排序依据 📌 示例 1:按字符串长度排序 1 2 words = ['apple' , 'banana' , 'pear' , 'kiwi' ]print (sorted (words, key=len ))
📌 示例 2:忽略大小写排序 1 2 words = ['Banana' , 'apple' , 'Cherry' ]print (sorted (words, key=str .lower))
✅ 6. 排序字典列表(企业常用) 📌 示例 1:按年龄排序员工列表 1 2 3 4 5 6 7 8 9 10 employees = [ {"name" : "Alice" , "age" : 30 }, {"name" : "Bob" , "age" : 25 }, {"name" : "Tom" , "age" : 35 } ] sorted_employees = sorted (employees, key=lambda emp: emp["age" ])for e in sorted_employees: print (e["name" ], e["age" ])
✅ 输出:
📌 示例 2:按多个字段排序(先按年龄,再按姓名) 1 2 3 4 5 6 7 8 9 10 employees = [ {"name" : "Alice" , "age" : 30 }, {"name" : "Bob" , "age" : 25 }, {"name" : "Alice" , "age" : 25 } ] sorted_employees = sorted (employees, key=lambda e: (e["age" ], e["name" ]))for e in sorted_employees: print (f'{e["name" ]} - {e["age" ]} ' )
✅ 7. 复杂数据结构排序(企业实战) 📌 按文件大小排序(模拟文件信息) 1 2 3 4 5 6 7 8 9 10 files = [ {"filename" : "report.docx" , "size" : 2400 }, {"filename" : "data.xlsx" , "size" : 5000 }, {"filename" : "image.png" , "size" : 3200 }, ] largest_first = sorted (files, key=lambda f: f["size" ], reverse=True )for f in largest_first: print (f["filename" ], f["size" ])
✅ 输出:
1 2 3 data .xlsx 5000 image .png 3200 report .docx 2400
✅ 8. 与自定义函数结合 1 2 3 4 5 def get_last_digit (num ): return num % 10 nums = [23 , 41 , 56 , 77 ]print (sorted (nums, key=get_last_digit))
✅ 9. 使用 operator
模块简化排序 1 2 3 4 5 6 7 8 9 10 from operator import itemgetter employees = [ {"name" : "Alice" , "age" : 30 }, {"name" : "Bob" , "age" : 25 }, {"name" : "Tom" , "age" : 35 } ] sorted_list = sorted (employees, key=itemgetter("age" ))
✅ 10. 不使用 sorted()
的影响 ❌ 手动排序效率低 & 不安全 1 2 3 4 5 for i in range (len (scores)): for j in range (i + 1 , len (scores)): if scores[i] > scores[j]: scores[i], scores[j] = scores[j], scores[i]
🔴 问题:
❌ 手写排序容易出错
❌ 可读性差
❌ 无法快速切换排序依据
✅ sorted()
性能优化好、支持多条件、key 定制灵活
✅ 11. 函数式编程中的 sorted()
结合 map
、filter
、lambda
:
1 2 3 4 products = ["book" , "TV" , "laptop" , "pen" , "speaker" ] result = sorted (filter (lambda x: len (x) > 3 , products))print (result)
✅ 12. 总结:sorted()
的强大之处
功能
使用方式
优点
基本排序
sorted(list)
升序、稳定排序
降序排序
sorted(list, reverse=True)
快速实现降序
自定义排序
key=lambda x: ...
灵活
多字段排序
key=lambda x: (a, b)
企业数据处理场景
不修改原始数据
返回新列表
更安全
可排序任意可迭代对象
dict, tuple, set
等
更通用
✅ 企业场景建议
场景
推荐方式
排序列表中的数字或字符串
sorted(list)
对复杂对象如字典排序
key=lambda x: x["key"]
多字段排序
key=lambda x: (x["a"], x["b"])
处理大数据列表
sorted()
+key
+reverse
组合
工具型模块
使用operator.itemgetter
提高效率
🧠 记住 :sorted()
是 Python 数据处理的必备工具 ,写清楚排序逻辑,让你的代码更清晰、更安全、更优雅。掌握 key
和 reverse
,你就掌握了数据排序的核心。
🚀 从现在开始,让你的排序从手动实现 → Pythonic 优雅!