MST

星途 面试题库

面试题:Python列表sort排序自定义比较函数

有一个列表students = [{'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 18}, {'name': 'Charlie', 'age': 22}],请使用sort方法按照学生的年龄从大到小进行排序,并输出排序后的列表。要求使用自定义比较函数实现。
40.0万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
students = [{'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 18}, {'name': 'Charlie', 'age': 22}]

def compare_students(student):
    return student['age']

students.sort(key=compare_students, reverse=True)
print(students)

排序后的列表为:

[{'name': 'Charlie', 'age': 22}, {'name': 'Alice', 'age': 20}, {'name': 'Bob', 'age': 18}]