【问题标题】:apply list of function to an iterable one after another in python在python中一个接一个地将函数列表应用于可迭代
【发布时间】:2021-02-25 05:36:08
【问题描述】:

我有一个函数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中有没有办法做到这一点?

【问题讨论】:

  • 如果第一个函数是lambda c: c.upper() * 2,你想得到"AA0BB0CC0DD0"还是"A0A0B0B0C0C0D0D0"
  • 后一个 - A0A0B0B0C0C0D0D0.

标签: python python-3.x lambda functional-programming reduce


【解决方案1】:

您可以将functools.reduce 与参数一起使用

  1. as function : 将当前函数应用于上一个结果
  2. as sequence : 函数列表
  3. as initial value : 初始字符串
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

【讨论】:

    猜你喜欢
    • 2016-05-14
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-04
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多