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 —— 取完了。
    """

  • 相关阅读:
    spring cloud的pigx版本
    SQL Profiler使用
    postmen简单用法
    T-SQL
    常见问题整理
    数据库 新建维护计划
    c# ABP返回格式自定义,去除固定返回格式
    系统综合实践期末大作业 第32组
    系统综合实践第7次实践作业 第32组
    系统综合实践第6次实践作业 第32组
  • 原文地址:https://www.cnblogs.com/yujiemeigui/p/14611115.html
Copyright © 2011-2022 走看看