zoukankan      html  css  js  c++  java
  • 使用高阶函数求所有学生的总分数

     示例代码:

    students = [
        {'name': 'hw', 'age': 18, 'score': 87, 'height': 175},
        {'name': 'lisa', 'age': 16, 'score': 97, 'height': 155},
        {'name': 'liheqing', 'age': 20, 'score': 90, 'height': 157},
        {'name': 'huangwei', 'age': 24, 'score': 67, 'height': 185},
        {'name': 'cx', 'age': 22, 'score': 56, 'height': 180},
        {'name': 'wei', 'age': 17, 'score': 89, 'height': 176},
    ]
    
    from functools import reduce
    
    
    # 给[x]的值 设定一个初始值 【0】
    result2 = reduce((lambda x, y: x + y['score']), students, 0)
    print(result2)  # 87 + 97 + 90 + 67 + 56 + 89 = 486 
    View Code

     

    运行结果分析:

    """
      给reduce函数添加第三个参数,值为0的情况下,根据reduce函数的运算规则,执行流程:
      第一次:
        x —— 0
        y —— y['score'] = 87
      第二次:
        x —— 87 # 0 + 87 = 87
        y —— y['score'] = 97
      第三次:
        x —— 184 # 87 + 97 = 184
        y —— y['score'] = 90
      第四次:
        x —— 274 # 184 + 90 = 274
        y —— y['score'] = 67
      第五次:
        x —— 341 # 274 + 67 = 341
        y —— y['score'] = 56
      第六次:
        x —— 87 # 341 + 56 = 397
        y —— y['score'] = 89
      第七次:
        x —— 87 # 397 + 89 = 486
        y —— 取完了。
    """

  • 相关阅读:
    java 编程基础 Class对象 反射:代理模式和静态代理
    sql优化(排序)
    Mysql备份恢复
    Mysql5.7.33安装
    Networker oracle备份恢复
    Centos7 安装11.2.0.4
    spring security 自定义多种方式登录授权
    CentOS 7 安装Nginx 并配置自动启动
    Nginx 配置模板
    Alibaba cloud 版本说明
  • 原文地址:https://www.cnblogs.com/yujiemeigui/p/14611115.html
Copyright © 2011-2022 走看看