根据函数计算列表元素之和

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,我们可以使用 map() 函数将一个函数应用于列表的每个元素,并返回一个包含修改后值的新列表。我们还可以使用 sum() 函数来计算列表的总和。在这个挑战中,你需要编写一个函数,该函数接受一个列表和一个函数作为参数,使用提供的函数将列表的每个元素映射到一个值,并返回这些值的总和。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/DataStructuresGroup -.-> python/dictionaries("Dictionaries") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/comments -.-> lab-13723{{"根据函数计算列表元素之和"}} python/lists -.-> lab-13723{{"根据函数计算列表元素之和"}} python/tuples -.-> lab-13723{{"根据函数计算列表元素之和"}} python/dictionaries -.-> lab-13723{{"根据函数计算列表元素之和"}} python/function_definition -.-> lab-13723{{"根据函数计算列表元素之和"}} python/lambda_functions -.-> lab-13723{{"根据函数计算列表元素之和"}} python/build_in_functions -.-> lab-13723{{"根据函数计算列表元素之和"}} end

根据函数计算列表元素之和

编写一个函数 sum_by(lst, fn),它接受一个列表 lst 和一个函数 fn 作为参数。该函数应使用提供的函数将列表的每个元素映射到一个值,并返回这些值的总和。

def sum_by(lst, fn):
  return sum(map(fn, lst))
sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) ## 20

总结

在这个挑战中,你学习了如何使用 map()sum() 函数,在使用提供的函数将列表的每个元素映射到一个值之后,计算该列表的总和。这是一项有用的技术,可用于许多不同的场景,例如数据处理和分析。