找到匹配值

PythonPythonBeginner
立即练习

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

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

简介

在 Python 中,我们可以使用列表推导式和 next() 来找到给定列表中满足提供的测试函数的第一个元素的值。这在许多场景中都很有用,例如在列表中找到第一个奇数或第一个以某个字母开头的字符串。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/AdvancedTopicsGroup(["Advanced Topics"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/AdvancedTopicsGroup -.-> python/iterators("Iterators") subgraph Lab Skills python/comments -.-> lab-13640{{"找到匹配值"}} python/conditional_statements -.-> lab-13640{{"找到匹配值"}} python/for_loops -.-> lab-13640{{"找到匹配值"}} python/lists -.-> lab-13640{{"找到匹配值"}} python/tuples -.-> lab-13640{{"找到匹配值"}} python/function_definition -.-> lab-13640{{"找到匹配值"}} python/lambda_functions -.-> lab-13640{{"找到匹配值"}} python/build_in_functions -.-> lab-13640{{"找到匹配值"}} python/iterators -.-> lab-13640{{"找到匹配值"}} end

找到匹配值

编写一个名为 find(lst, fn) 的函数,它接受一个列表 lst 和一个测试函数 fn 作为参数。该函数应返回 lst 中第一个使 fn 返回 True 的元素的值。如果没有元素满足测试函数,该函数应返回 None

def find(lst, fn):
  return next(x for x in lst if fn(x))
find([1, 2, 3, 4], lambda n: n % 2 == 1) ## 1

总结

在这个挑战中,你学习了如何使用列表推导式和 next() 来找到列表中满足提供的测试函数的第一个元素的值。这种技术在许多场景中都很有用,并且可以帮助你编写更高效、更简洁的代码。