使用 Python 进行函数组合

PythonPythonBeginner
立即练习

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

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

简介

函数组合是函数式编程中使用的一种技术,用于将两个或多个函数组合成一个新函数。在 Python 中,我们可以使用 functools.reduce() 函数来执行从右到左的函数组合。


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(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/keyword_arguments("Keyword Arguments") python/FunctionsGroup -.-> python/lambda_functions("Lambda Functions") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") subgraph Lab Skills python/comments -.-> lab-13607{{"使用 Python 进行函数组合"}} python/tuples -.-> lab-13607{{"使用 Python 进行函数组合"}} python/function_definition -.-> lab-13607{{"使用 Python 进行函数组合"}} python/keyword_arguments -.-> lab-13607{{"使用 Python 进行函数组合"}} python/lambda_functions -.-> lab-13607{{"使用 Python 进行函数组合"}} python/importing_modules -.-> lab-13607{{"使用 Python 进行函数组合"}} python/using_packages -.-> lab-13607{{"使用 Python 进行函数组合"}} python/standard_libraries -.-> lab-13607{{"使用 Python 进行函数组合"}} end

组合函数

编写一个名为 compose(*fns) 的函数,它接受一个或多个函数作为参数,并返回一个新函数,该新函数是从右到左组合输入函数的结果。最后一个(最右边的)函数可以接受一个或多个参数;其余函数必须是一元函数。

from functools import reduce

def compose(*fns):
  return reduce(lambda f, g: lambda *args: f(g(*args)), fns)
add5 = lambda x: x + 5
multiply = lambda x, y: x * y
multiply_and_add_5 = compose(add5, multiply)
multiply_and_add_5(5, 2) ## 15

总结

在这个挑战中,你学习了如何使用 functools.reduce() 函数在 Python 中执行从右到左的函数组合。你还编写了一个名为 compose() 的函数,它接受一个或多个函数作为参数,并返回一个新函数,该新函数是从右到左组合输入函数的结果。