有条件地应用函数

PythonPythonBeginner
立即练习

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

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

简介

在 Python 中,函数是一等公民,这意味着它们可以像任何其他值一样被传递。这种特性的一个有用应用是根据某个谓词有条件地将一个函数应用于一个值。在这个挑战中,你将被要求编写一个函数,它接受一个谓词函数和一个在谓词为真时要应用的函数,并返回一个新函数,该新函数在谓词为真时应用该函数。


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(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") subgraph Lab Skills python/comments -.-> lab-13742{{"有条件地应用函数"}} python/conditional_statements -.-> lab-13742{{"有条件地应用函数"}} python/tuples -.-> lab-13742{{"有条件地应用函数"}} python/function_definition -.-> lab-13742{{"有条件地应用函数"}} python/lambda_functions -.-> lab-13742{{"有条件地应用函数"}} end

条件为真时应用函数

编写一个名为 when 的函数,它接受两个参数:一个谓词函数 predicate 和一个在条件为真时要应用的函数 when_truewhen 函数应返回一个新函数,该新函数接受单个参数 x。这个新函数应检查 predicate(x) 的值是否为 True。如果是,新函数应调用 when_true(x) 并返回结果。否则,新函数应返回 x

def when(predicate, when_true):
  return lambda x: when_true(x) if predicate(x) else x
double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2)
double_even_numbers(2) ## 4
double_even_numbers(1) ## 1

总结

在这个挑战中,你编写了一个函数,它根据某个谓词有条件地将一个函数应用于一个值。这是一种用于创建更灵活、更可复用代码的有用技术。