如何在 Python 中组合或链接多个函数

问题描述 投票:0回答:1

在编写程序时,我经常想对一段数据(通常是列表或字符串)执行一系列步骤。例如,我可能想调用一个返回字符串的函数,将其转换为列表,映射列表,然后归约以获得最终结果。

在我过去使用过的编程语言中,我希望能够执行以下操作之一:

compose(
  getSomeString,
  list,
  map(someMapFunction)
  reduce(someReduceFunction)
)()
getSomeString()
  .list()
  .map(someMapFunction)
  .reduce(someReduceFunction)
getSomeFunction
  => list
  => map(someMapFunction)
  => reduce(someReduceFunction)()

但是,我无法找到一种干净而紧凑的方法来在 Python 中进行组合/链接。我发现的一个例外是列表理解适用于我想要组成地图和过滤器的情况。

在没有大量嵌套的情况下编写面向组合的代码的 Python 方式是什么,这使得我的代码看起来像 Lisp:

reduce(
  someReduceFunction,
  map(
    someMapFunction,
    list(
      getSomeString()
    )
  )
)

或者为一切创造中间值:

myString = getSomeString()
stringAsList = list(myString)
mappedString = map(someMapFunction, stringAsList)
reducedString = reduce(someReduceFunction, mappedString)
python python-3.x method-chaining function-composition
1个回答
1
投票

如果你不介意编写自己的实用函数,像这样就可以了:

def compose(*functions):
  def pipe(value):
    for f in functions:
      value = f(value)
    return value

  return pipe

然后您可以将其用作:

from functools import partial

compose(
  getSomeString,
  list,
  partial(map, someMapFunction)
  partial(reduce, someReduceFunction)
)("input")

缺点是它只能传递单个返回值

© www.soinside.com 2019 - 2024. All rights reserved.