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

  • 相关阅读:
    Solr环境配置
    SolrJ解析MoreLikeThis查询结果
    思维导图软件PersonalBrain 6.0.6.4破解版使用
    离散对数-详解
    转:pptp和l2tp的区别
    DiffieHellman Key Exchange (DH)源代码
    磁盘IOPS计算
    转:TCP/IP Network Performance Benchmarks and Tools
    转:弄清楚你的业务类型——OLTP or OLAP
    U8软件的端口
  • 原文地址:https://www.cnblogs.com/yujiemeigui/p/14611115.html
Copyright © 2011-2022 走看看