【问题标题】:How to compose a list of functions in steps in Python using map and reduce如何使用 map 和 reduce 在 Python 中按步骤组成函数列表
【发布时间】:2018-10-05 07:00:03
【问题描述】:

给定一个函数(函数)列表和一个整数 n,我试图找出一种逐步组合它们的方法,并返回每个逐步结果的列表,如下所示:

compose_step([lambda x: x+3, lambda x: x+5, lambda x: x+1], 8) --> [8, 11, 16, 17]

所以,到目前为止,我已经想出了如何组成一个函数列表并返回结果如下:

def compose(functions, n):
    def compose2(f,g):
        return lambda x: f(g(x))
    composedFunction = functools.reduce(compose2, functions, lambda x: x)
    return composedFunction(n)

但是,我非常困惑如何跟踪每个步骤并将其作为列表返回。我假设我需要以某种方式使用 map 以便将每个逐步映射到列表。我还想出了一个方法来将列表中的所有函数都应用到 n 上:

def apply_all_functions(functions, n):
    answerList = list(map(methodcaller('__call__', n), functions)))
    return answerList

我正在考虑以某种方式使用 composeFunction 函数来组成一个新的逐步函数列表,一直到完全组合的函数,然后将其用作 apply_all_functions 的新列表,以实现所需的结果。但目前,我很困惑。

【问题讨论】:

  • 你能解释一下你在这里的目的是什么吗?我不明白您的输入和预期输出是什么。

标签: python dictionary functional-programming reduce


【解决方案1】:

您可以将itertools.accumulate 与合成功能一起使用

from itertools import accumulate

def compose(f, g):
    return lambda x: f(g(x))

funcs = [lambda x: x, lambda x: x+3, lambda x: x+5, lambda x: x+1]

print([f(8) for f in accumulate(funcs, compose)])
# [8, 11, 16, 17]

【讨论】:

    【解决方案2】:

    itertools.accumulate 是可行的方法,但如果您想知道如何自己做到这一点,这里有一种方法

    def apply_all (x, f = None, *fs):
      if f is None:
        return []
      else:
        next = f (x)
        return [ next ] + apply_all(next, *fs)
    
    funcs = \
      [ lambda x: x
      , lambda x: x+3
      , lambda x: x+5
      , lambda x: x+1
      ]
    
    print(apply_all(8, *funcs))
    # [ 8, 11, 16, 17 ]
    

    如果您需要原始问题中的表格

    def apply_all (fs, x):
      if not fs:
        return []
      else:
        next = fs[0](x)
        return [ next ] + apply_all(fs[1:], next)
    
    funcs = \
      [ lambda x: x
      , lambda x: x+3
      , lambda x: x+5
      , lambda x: x+1
      ]
    
    print(apply_all(funcs, 8))
    # [ 8, 11, 16, 17 ]
    

    上述形式在fs[0]fs[1:] 上运行,这表明这可以表示为香草reduce

    from functools import reduce
    
    def apply_all (fs, x):
      def reducer (acc, f):
        (seq, x) = acc
        next = f (x)
        return (seq + [next], next)
      return reduce(reducer, fs, ([], x)) [0]
    
    funcs = \
      [ lambda x: x
      , lambda x: x+3
      , lambda x: x+5
      , lambda x: x+1
      ]
    
    print(apply_all(funcs, 8))
    # [ 8, 11, 16, 17 ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-21
      • 2013-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多