【发布时间】:2013-08-21 09:16:17
【问题描述】:
我有一个函数数组:
functions = [function_a,function_b,square,...,last_function]
我想在一行的变量中获取 function_a(function_b(square(...(last_function("hello"))..))) 的输出,用列表理解技巧替换点。
像这样:
tmp = input
for f in functions:
tmp = f(tmp)
output = tmp
不使用tmp,在一行中。
【问题讨论】:
-
reduce(lambda x, y: x(y), [functions, ...])有效吗?只是猜测 -
顺便说一句,你的代码是
last_fuction(...(square(function_b(function_a("hello")))))。 -
是的,你是对的。我知道这一点,但在我的问题中顺序并不重要。
-
列表推导式创建一个列表;您实际上想将列表减少为单个值,这就是
reduce所做的(Python 3 中的functools.reduce)。