使用高阶函数求所有学生的总分数

 

 示例代码:

 

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

posted @ 2021-04-02 16:02  御姐玫瑰  阅读(202)  评论(0编辑  收藏  举报
levels of contents