我想将函数列表fs = [ f, g, h ]按顺序应用于字符串text=' abCdEf '
就像是f( g( h( text) ) )。
这可以通过以下代码轻松完成:
# 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)
Run Code Online (Sandbox Code Playgroud)
似乎functools.reduce应该在这里完成工作,因为它在每次迭代时“消耗”函数列表。
from functools import reduce
# I know `reduce` requires two arguments, but I don't …Run Code Online (Sandbox Code Playgroud)