小编Jay*_*ave的帖子

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

问题陈述

我想将函数列表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 …
Run Code Online (Sandbox Code Playgroud)

python reduce list-comprehension fold functools

5
推荐指数
1
解决办法
1076
查看次数

标签 统计

fold ×1

functools ×1

list-comprehension ×1

python ×1

reduce ×1