一、列表排序
demoList = [1, 3, 2, 4, 9 ,7]res = sorted(demoList) # 默认升序# 降序
# res = sorted(demoList, reverse=True)print(res)
二、字典排序
demoDict = {"篮球": 5, "排球": 9, "网球": 6, "足球": 3}# sorted排序
res = sorted(demoDict.items(),key=lambda x:x[1])
print(res)
# sort排序,其实将字典转成<<列表+元组>>格式排序
newList = list(demoDict.items()) # [('篮球', 5), ('排球', 9), ('网球', 6), ('足球', 3)]
newList.sort(key=lambda x:x[1])
print(newList)
print(dict(newList))
三、<<列表+字典>>排序
demoList = [{"name": "张三", "age": 16}, {"name": "李四", "age": 24}, {"name": "王五", "age": 20}, {"name": "赵六", "age": 18}
]sorted(demoList, key=lambda x:x["age"])
四、<<列表+元组>>排序
- 在 (二、字典排序)中有介绍
五、<<列表+列表>>排序
demoList = [["张三", 16, "北京市"], ["李四", 24, "上海市"], ["王五", 20, "广州市"], ["赵六", 18, "深圳市"]
]sorted(demoList, key=lambda x:x[1])
六、<<列表+对象>>排序
class Student:def __init__(self, name, grade, age):self.name = nameself.grade = gradeself.age = agedef __repr__(self):return repr((self.name, self.grade, self.age))stuObj = [Student('john', 'A', 15),Student('jane', 'B', 12),Student('dave', 'B', 10),
]sorted(stuObj, key=lambda x: x.age)
七、<<列表+字典运算>>排序
demoList = [{'key1': 1, 'key2': 1}, {'key1': 5, 'key2': 1}, {'key1': 3, 'key2': 6}, {'key1': 2, 'key2': 3}, {'key1': 4, 'key2': 9}
]demoList.sort(key=lambda x:x["key1"]+x["key2"])
print(demoList)
八、高级拓展
8.1、None值无法被排序
demoList = [{"name": "张三", "age": 16}, {"name": "李四", "age": 24}, {"name": "王五", "age": 20}, {"name": "赵六", "age": 18},{"name": "孙七", "age": None}
]
- 解决方式
demoList.sort(key=lambda x:(x["age"] is None, x["age"] == "", x["age"]))
print(demoList)
8.2、字典取最大|小值
demoDict = {"篮球": 5, "排球": 9, "网球": 6, "足球": 3}# 最大值
maxData = max(demoDict.items(), key=lambda x:x[1])
print(maxData)
# 最小值
minData = min(demoDict.items(), key=lambda x:x[1])
print(minData)
8.3、多重条件排序
demoList = [{"name": "诺基亚K", "price": 2399, "level": 1}, {"name":"魅族", "price": 2499, "level": 3},{"name": "中兴E", "price": 2399, "level": 3}, {"name": "vivoZ", "price": 2799, "level": 2}, {"name": "oppoT", "price": 2699, "level": 2}, {"name": "小米Y", "price": 2999, "level": 2}, {"name": "华为X", "price": 2999, "level": 1}, {"name": "苹果P", "price": 5799, "level": 1}, {"name": "三星W", "price": 5799, "level": 1}
]# 两重查询条件,价格(默认升序)、级别(默认升序)
sorted(demoList, key=lambda x:(x["price"], x["level"]))
# 两重查询条件,价格(默认升序)、级别(降序可以用-)
sorted(demoList, key=lambda x:(x["price"], -x["level"]))
- 价格⬆级别⬆
- 价格⬆级别⬇
8.4、operator实现排序
- 排序的思想同匿名函数lambda一样
# 举个字典排序
demoDict = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}# lambda排序
sorted(demoDict.items(), key=x: x[1])# operator排序
import operator
sorted(demoDict.items(), key=operator.itemgetter(1))# 仔细看其实排序都是一样的,无非是换种写法
8.5、多层列表字典排序
demoDict = {"a": [{"key": 2}], "c": [{"key": 1}], "b": [{"key": 3}]
}sorted(demoDict.items(), key=lambda x:x[1][0]["key"])
print(demoDict)
print(dict(demoDict))