Python中如何替代reduce实现函数多次自应用?是否有类似Nest的函数?
替代reduce处理单参数函数重复调用的方案
当你需要重复调用单参数函数(比如多次执行dirname)时,完全没必要用reduce配合忽略参数的lambda,Python可以通过自定义类似Mathematica Nest的函数来解决,写法更直观清晰。
自定义Nest函数
最直接的方式是自己实现一个nest函数,专门用来将单参数函数重复应用指定次数:
from os.path import dirname def nest(func, repeat_times, initial_value): current = initial_value for _ in range(repeat_times): current = func(current) return current # 使用示例,等效于原reduce写法 result = nest(dirname, 3, __file__)
这个函数逻辑简单:从初始值开始,循环repeat_times次调用目标函数,每次把结果作为下一次的输入,完全对应Mathematica中Nest的行为,而且代码可读性远高于reduce加临时lambda的写法。
其他简洁写法(可选)
如果不想单独定义函数,也可以用基础循环实现:
from os.path import dirname # 次数少的时候直接链式调用 result = dirname(dirname(dirname(__file__))) # 次数较多时用循环 result = __file__ for _ in range(3): result = dirname(result)
不过当重复次数不确定或需要复用逻辑时,自定义nest函数是更优的选择。
内容的提问来源于stack exchange,提问作者Mefitico
相关产品推荐
相关产品推荐

