• python 学习笔记2 匿名函数


    # 匿名函数  lambda a,b : a+b
    # a.j.
    from functools import reduce

    students = [{'name': '张三', 'age': 18, 'height': 188},
    {'name': '李四', 'age': 17, 'height': 178},
    {'name': '王五', 'age': 19, 'height': 186}]
    # 按height排序 reverse=True 反向
    resultSorted = sorted(students, key=lambda x: x['height'], reverse=True)
    print('resultSorted: {}'.format(list(resultSorted)))

    # 求age最大
    resultMax = max(students, key=lambda x: x['age'])
    print('resultMax: {}'.format(resultMax))

    # 求heght最小
    resultMin = min(students, key=lambda x: x['height'])
    print('resultMin: {}'.format(resultMin))

    # 筛选age大于17的字典
    resultFilter = filter(lambda x: x['age'] > 17, students)
    print('resultFilter: {}'.format(list(resultFilter)))

    # 每个age元素都+2
    resultMap = 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': 19, 'height': 186}
    resultMin:{'name': '李四', 'age': 17, 'height': 178}
    resultFilter: [
      {'name': '张三', 'age': 18, 'height': 188},
      {'name': '王五', 'age': 19, 'height': 186}]

    resultMap: [20, 19, 21]

    resultReduce: 45
    '''
  • 相关阅读:
    友元类和友元函数
    C++中构造函数和析构函数调用的时机
    Linux 下svn恢复到某一版本
    lua 中pairs 和 ipairs区别
    孤儿进程与僵尸进程
    union
    关于C++ const 的全面总结
    后台管理左侧菜单
    全选-反选-取消
    Dom-直接 /间接选择器
  • 原文地址:https://www.cnblogs.com/alchemist-z/p/12217919.html
Copyright © 2020-2023  润新知