映射列表的平均值

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/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) 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/default_arguments("Default Arguments") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/comments -.-> lab-13588{{"映射列表的平均值"}} python/lists -.-> lab-13588{{"映射列表的平均值"}} python/tuples -.-> lab-13588{{"映射列表的平均值"}} python/dictionaries -.-> lab-13588{{"映射列表的平均值"}} python/function_definition -.-> lab-13588{{"映射列表的平均值"}} python/default_arguments -.-> lab-13588{{"映射列表的平均值"}} python/lambda_functions -.-> lab-13588{{"映射列表的平均值"}} python/build_in_functions -.-> lab-13588{{"映射列表的平均值"}} end

映射列表的平均值

编写一个名为 average_by(lst, fn = lambda x: x) 的函数,该函数接受一个列表 lst 和一个函数 fn 作为参数。函数 fn 应用于列表的每个元素,将其映射为一个值。然后,该函数应计算这些映射值的平均值并返回。

如果未提供 fn 参数,函数应使用默认的恒等函数,该函数直接返回元素本身。

你的函数应满足以下要求:

  • 使用 map() 将每个元素映射为 fn 返回的值。
  • 使用 sum() 对所有映射值求和,再除以 len(lst)
  • 省略最后一个参数 fn 以使用默认的恒等函数。

函数签名:def average_by(lst, fn = lambda x: x) -> float:

def average_by(lst, fn = lambda x: x):
  return sum(map(fn, lst), 0.0) / len(lst)
average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n'])
## 5.0

总结

在这个挑战中,我们学习了如何在使用提供的函数将列表的每个元素映射到一个值之后,使用 map()sum() 函数来计算列表的平均值。我们还学习了如何在 Python 函数中使用默认参数。