如何使用 Python reduce 或列表理解将函数列表按顺序应用于字符串?

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

似乎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,reducelist comprehension来解决这个问题?

Ste*_*tef 7

reduce可以采用三个参数:

reduce(function, iterable, initializer)
Run Code Online (Sandbox Code Playgroud)

这三个论点一般来说是什么?

  • function是两个参数的函数。我们将这两个参数称为tf
  • 第一个参数 ,t将以initializer;开头 then 将继续作为上一次调用的返回值function
  • 第二个参数f取自iterable

在我们的案例中,这三个论点是什么?

  • 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)