问题陈述
我想将函数列表fs = [ f, g, h ]
按顺序应用于字符串text=' abCdEf '
大约f( g( h( text) ) )
,其中f,g,h in fs
这可以通过以下代码轻松实现:
# initial text
text = ' abCDef '
# list of functions to apply sequentially
fs = [str.rstrip, str.lstrip, str.lower]
for f in fs:
text = f(text)
# expected result is 'abcdef' with spaces stripped, and all lowercase
print(text)
使用列表理解
我try 使用列表理解,但它只是创建了每个函数调用的列表:
[ f(text) for f in fs ]
[' abCDef', 'abCDef ', ' abcdef ']
使用工具.减少
似乎functools.reduce
应该在这里完成这项工作,因为它在每次迭代中"消耗"函数列表.
from functools import reduce
reduce(f(text), fs)
# first interaction should call
y = str.rstrip(' abCDef ') --> ' abCDef'
# next iterations fails, because tries to call ' abCDef'() -- as a function
不幸的是,这段代码不起作用,因为每次迭代都会返回函数的string个istead,但以TypeError: 'str' object is not callable
个istead失败.