排序1

时间:2020-12-30 00:37:56
# 1.对字典进行排序
dic_demo = {
"2101": 1,
"2102": 3,
"2103": 2,
}
res = sorted(dic_demo.items(), key=lambda x: x[1], reverse=False) # 从小到大
# res [('2101', 1), ('2103', 2), ('2102', 3)]
res = sorted(dic_demo.items(), key=lambda x: x[1], reverse=True) # 从大到小
# res [('2102', 3), ('2103', 2), ('2101', 1)]

# 2.对数组进行排序
arr = [
{"name": "小明", "age": 18},
{"name": "小红", "age": 99},
{"name": "木木", "age": 22},
]
res = sorted(arr, key=lambda x: x["age"], reverse=False) # 从小到大
# res [{'name': '小明', 'age': 18}, {'name': '木木', 'age': 22}, {'name': '小红', 'age': 99}]
res = sorted(arr, key=lambda x: x["age"], reverse=True) # 从大到小
# res [{'name': '小红', 'age': 99}, {'name': '木木', 'age': 22}, {'name': '小明', 'age': 18}]