2016-08-24 89 views

回答

17

使用reduce() function

# forward-compatible import 
from functools import reduce 

result = reduce(lambda res, f: f(res), funcs, val) 

reduce()适用的第一个参数,一个可调用的,以从第二个参数采取的每个元素,加上到目前为止累加结果(如(result, element))。第三个参数是一个初始值(否则将使用funcs中的第一个元素)。

在Python 3中,内置函数被移动到functools.reduce() location;为了兼容性,Python 2.6及更高版本中提供了相同的参考。

其他语言可能会调用这个folding

如果您需要中间结果为每个功能也使用itertools.accumulate()(只在Python 3.3起的版本,需要一个函数参数):

from itertools import accumulate, chain 
running_results = accumulate(chain(val, funcs), lambda res, f: f(res)) 
+0

完美的答案,你可以使用它们!我喜欢OCaml的'List.fold_left',而在Python中我们有'functools.reduce()':) – Viet

+2

@Viet:参见[Wikipedia的各种编程语言中的* fold *](https://en.wikipedia.org /维基/ Fold_(更高order_function)#Folds_in_various_languages)。 –

1

MartijnPieters回答非常出色。我想补充的唯一的事情是,这是所谓的function composition

给予名称,以这些仿制药是指每当有需要时

from functools import reduce 

def id(x): 
    return x 

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

def compose(*fs): 
    return reduce(comp, fs, id) 

# usage 
# compose(f1, f2, f3, ..., fn) (val) 

print(compose (lambda x: x + 1, lambda x: x * 3, lambda x: x - 1) (10)) 
# = ((10 - 1) * 3) + 1 
# = 28 
+0

感谢您的加入,@naomik:D – Viet