sort 函数的参数(特别是 key 和 reverse)是用来告诉 Python“按照什么规则”来排序的。data.sort() 不带任何参数时,Python 会按照 “字典序” (Lexicographical Order) 进行排序。核心规则:从左到右,依次比较
如果里面是多个字典,L = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 20}]
L.sort() 不带任何参数时:🚨
结果:直接报错!(TypeError)
TypeError: '<' not supported between instances of 'dict' and 'dict'场景 1:按某个特定的键排序(最常用)
"age" 从小到大排:x 代表列表中的每一个字典(如 {"name": "Alice", "age": 25})。x["age"] 取出年龄数字。1. key 参数:定义“排序依据” (最重要!)
L.sort(key=lambda x: order_map[x[0]])
(4, 'c') 和 (1, 'a') 谁大谁小(因为元组比较复杂)。请先把它们转换成 order_map里的排名分数(比如 3 和 0),然后只比分数!”key=len:按字符串长度排序(短的在前)。key=lambda x: x[1]:按元组的第二个元素排序。key=str.lower:按字母忽略大小写排序reverse 参数:定义“排序方向”
True 或 False)。False(升序,从小到大)。True:降序(从大到小)。
想按照自定义的特定顺序排序
[1, 2, 5, 4, 9] 是想表达:“我希望结果严格按照 1, 2, 5, 4, 9 这个顺序排列,而不是自然的大小顺序”。key 函数返回每个元素在这个自定义列表中的索引位置。L = [(1,"a"),(2,"b"),(5,"e"),(9,"f"),(4,"c")]
custom_order = [1, 2, 5, 4, 9]
# 创建一个映射:{1:0, 2:1, 5:2, 4:3, 9:4}
# 这样排序时,1的权重是0(最小),9的权重是4(最大)
order_map = {val: i for i, val in enumerate(custom_order)}
L.sort(key=lambda x: order_map[x[0]]) print(L)
# 输出: [(1, 'a'), (2, 'b'), (5, 'e'), (4, 'c'), (9, 'f')]
# 注意:这里 5 排在了 4 前面,因为 custom_order 里 5 在 4 前面
遍历列表里的每一项 for item in list_to_sort: # item 就是列表里的某一项,比如 (4, "c") # 3. 【自动喂食】把这一项 (item) 作为参数,传给你提供的函数 (key_function) # 这里的 item 就变成了你函数里的 x