2016-08-24 90 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