7.7 lambda的应用

更新于 2026年10月13日 版权声明
7.7 lambda的应用

(1)带判断的lambda

print((lambda a, b: a if a > b else b)(1000, 500)) # 求两个数的最大值

(2)列表数据按字典key的值排序(https://www.daowen.com)

students = [
    {'name': 'Python', 'score': 88},
   {'name': 'MySQL', 'score': 90},
   {'name': 'Java', 'score': 87}
]
# 按score值降序排列  reverse=True
students.sort(key=lambda x: x['score'], reverse=True)
print(students)
# 按score值升序排列 默认为升序
students.sort(key=lambda x: x['score'])
print(students)

✍AI写作