根据函数查找列表中的最大值

PythonPythonBeginner
立即练习

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

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

简介

在 Python 中,我们可以使用 max() 函数来找到列表中的最大值。但是,如果我们想在使用提供的函数将每个元素映射到一个值之后找到最大值呢?在这个挑战中,你需要编写一个函数,该函数接受一个列表和一个函数作为参数,使用提供的函数将每个元素映射到一个值,然后返回最大值。


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/lambda_functions("Lambda Functions") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/comments -.-> lab-13686{{"根据函数查找列表中的最大值"}} python/lists -.-> lab-13686{{"根据函数查找列表中的最大值"}} python/tuples -.-> lab-13686{{"根据函数查找列表中的最大值"}} python/dictionaries -.-> lab-13686{{"根据函数查找列表中的最大值"}} python/function_definition -.-> lab-13686{{"根据函数查找列表中的最大值"}} python/lambda_functions -.-> lab-13686{{"根据函数查找列表中的最大值"}} python/build_in_functions -.-> lab-13686{{"根据函数查找列表中的最大值"}} end

根据函数查找列表中的最大值

编写一个函数 max_by(lst, fn),它接受一个列表 lst 和一个函数 fn 作为参数。该函数应使用提供的函数 fnlst 中的每个元素映射到一个值,然后返回最大值。

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

总结

在这个挑战中,你已经学会了如何在使用提供的函数将列表中的每个元素映射到一个值之后,找到列表中的最大值。你编写了一个函数 max_by(lst, fn),它接受一个列表和一个函数作为参数,使用提供的函数将每个元素映射到一个值,然后返回最大值。