在 python 中将函数列表一个接一个地应用于可迭代

apply list of function to an iterable one after another in python

我有一个函数 process,它接收一个函数列表和一个可迭代对象。我想将该列表中的每个函数一个接一个地应用于可迭代对象。我写的这个很好用但是...

def process(list_of_funcs, string):
  for func in list_of_funcs:
    string = ''.join(list(map(func, string)))
  return string

ans = process([lambda c: c.upper(), lambda c: c + '0'], "abcd")
print(ans) # A0B0C0D0

我想跳过 for 循环(并以函数式编程的方式进行)。在 python 中有办法吗?

您可以使用 functools.reduce 和参数

  1. as function : 将当前函数应用于上一个结果
  2. as sequence : 函数列表
  3. as initial 值:初始字符串
def process(list_of_funcs, string):
    return reduce(lambda res, f: ''.join(map(f, res)), list_of_funcs, string)

注意:不需要中间 listjoin 需要 iterator


这是一个包含 3 个函数的示例,它提供与您最初的 for 循环解决方案相同的输出

fcts = [lambda c: c.upper(), lambda c: c + '0', lambda c: c * 2]
ans = process(fcts, "abcd")
print(ans)  # AA00BB00CC00DD00