Python list.sort()排序
List中字典指定元素排序
array = [{"score": "98", "name": "lili", "age": 19},{"score": "98", "name": "chenming", "age": 18},
{"score": "88", "name": "wangxin", "age": 17}]
print("排序前:", array)
# 排序前: [{'score': '98', 'name': 'lili', 'age': 19}, {'score': '98', 'name': 'chenming', 'age': 18}, {'score': '88', 'name': 'wangxin', 'age': 17}]
array.sort(key=lambda x: x["score"])
print("指定单个元素排序:", array)
# 指定单个元素排序: [{'score': '88', 'name': 'wangxin', 'age': 17}, {'score': '98', 'name': 'lili', 'age': 19}, {'score': '98', 'name': 'chenming', 'age': 18}]
array.sort(key=lambda x: (x["score"], x["age"]))
print("指定多个元素排序:", array)
# 指定多个元素排序: [{'score': '88', 'name': 'wangxin', 'age': 17}, {'score': '98', 'name': 'chenming', 'age': 18}, {'score': '98', 'name': 'lili', 'age': 19}]
# list.sort()
alist = [1, 4, 2, 8, 5, 7, 6, 9, 3]
alist.sort()
print(alist) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
dict = [{"name": "AA", "age": 16}, {"name": "BB", "age": 14}]
# 按age倒序排序
result = sorted(dict, key=lambda x: x["age"], reverse=True)
print(result) # [{'name': 'AA', 'age': 16}, {'name': 'BB', 'age': 14}]
以上是 Python list.sort()排序 的全部内容, 来源链接: utcz.com/z/386522.html