Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 寻找一个类似褶皱的成语_Python_Python 3.x_Functional Programming - Fatal编程技术网

Python 寻找一个类似褶皱的成语

Python 寻找一个类似褶皱的成语,python,python-3.x,functional-programming,Python,Python 3.x,Functional Programming,所以我的朋友给我提出了一个需要解决的问题,我目前正在用函数式Python编写一个解决方案。问题本身不是我的问题;我在寻找一个可能的习语,但我目前找不到 我需要的是一个折叠,但不是对它的每个应用程序都使用相同的函数,而是像地图一样耗尽另一个包含函数的列表。例如,给定以下代码: nums = [1, 2, 3] funcs = [add, sub] special_foldl(nums, funcs) 函数(special_foldl)将使用((1+2)-3)向下折叠数字列表。是否有一个函数/习惯

所以我的朋友给我提出了一个需要解决的问题,我目前正在用函数式Python编写一个解决方案。问题本身不是我的问题;我在寻找一个可能的习语,但我目前找不到

我需要的是一个折叠,但不是对它的每个应用程序都使用相同的函数,而是像地图一样耗尽另一个包含函数的列表。例如,给定以下代码:

nums = [1, 2, 3]
funcs = [add, sub]
special_foldl(nums, funcs)

函数(special_foldl)将使用((1+2)-3)向下折叠数字列表。是否有一个函数/习惯用法可以很好地做到这一点,或者我应该自己使用吗?

Python标准库中没有这样的函数。你必须自己动手,也许是这样:

import operator
import functools

nums = [1, 2, 3]
funcs = iter([operator.add, operator.sub])

def special_foldl(nums, funcs):
    return functools.reduce(lambda x,y: next(funcs)(x,y), nums)

print(special_foldl(nums, funcs))
# 0