Jay*_*ave 5 python reduce list-comprehension fold functools
我想将函数列表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 even know
# which one to chose as text of function from the list
reduce(f(text), fs)
# first interaction should call
y = str.rstrip(' abCDef ') --> ' abCDef'
# next iterations fails, because tries to call ' abCDef'() -- as a function
Run Code Online (Sandbox Code Playgroud)
不幸的是,这段代码不起作用,因为每次迭代都会返回一个字符串而不是函数,并且失败并显示TypeError: 'str' object is not callable。
map,reduce或list comprehension来解决这个问题?reduce可以采用三个参数:
reduce(function, iterable, initializer)
Run Code Online (Sandbox Code Playgroud)
这三个论点一般来说是什么?
function是两个参数的函数。我们将这两个参数称为t和f。t将以initializer;开头 then 将继续作为上一次调用的返回值function。f取自iterable。在我们的案例中,这三个论点是什么?
f将是函数之一;t必须是文本;function必须是结果文本;function(t, f)必须是f(t)。最后:
from functools import reduce
# initial text
text = ' abCDef '
# list of functions to apply sequentially
fs = [str.rstrip, str.lstrip, str.lower]
result = reduce(lambda t,f: f(t), fs, text)
print(repr(result))
# 'abcdef'
Run Code Online (Sandbox Code Playgroud)