python 学习笔记2 匿名函数

混江龙づ霸主 提交于 2020-01-20 15:14:38
# 匿名函数  lambda a,b : a+b# a.j.from functools import reducestudents = [{'name': '张三', 'age': 18, 'height': 188},            {'name': '李四', 'age': 17, 'height': 178},            {'name': '王五', 'age': 19, 'height': 186}]# 排序  reverse=True 反向resultSorted = sorted(students, key=lambda x: x['height'], reverse=True)print('resultSorted: {}'.format(list(resultSorted)))# 最大resultMax = max(students, key=lambda x: x['age'])print('resultMax: {}'.format(list(resultMax)))# 最小resultMin = min(students, key=lambda x: x['height'])print('resultMin: {}'.format(list(resultMin)))# 筛选age大于17的字典resultFilter = filter(lambda x: x['age'] > 17, students)print('resultFilter: {}'.format(list(resultFilter)))# 每个元素都+2resultMap = map(lambda x: x['age'] + 2, students)print('resultMap: {}'.format(list(resultMap)))# 求和tupleReduce = (1, 2, 3, 4, 5, 6, 7, 8, 9)resultReduce = reduce(lambda a, b: a + b, tupleReduce)print('resultReduce: {}'.format(resultReduce))# 各个结果'''resultSorted: [{'name': '张三', 'age': 18, 'height': 188}, {'name': '王五', 'age': 19, 'height': 186}, {'name': '李四', 'age': 17, 'height': 178}]resultMax: ['name', 'age', 'height']resultMin: ['name', 'age', 'height']resultFilter: [{'name': '张三', 'age': 18, 'height': 188}, {'name': '王五', 'age': 19, 'height': 186}]resultMap: [20, 19, 21]resultReduce: 45'''
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!