Python:Reduce() 和函数作为函数的参数

在 Python3 中,我试图弄清楚 reduce() 和函数作为函数的参数,或者更好地将函数作为另一个函数的参数传递,其中第一个函数不明确,见下文


给定:


# define a function `call` where you provide the function and the arguments

def call(y,f):

    return f(y)


# define a function that returns the square

square = lambda x : x*x


# define a function that returns the increment

increment = lambda x : x+1


# define a function that returns the cube

cube = lambda x : x*x*x


# define a function that returns the decrement

decrement = lambda x : x-1


# put all the functions in a list in the order that you want to execute them

funcs = [square, increment, cube, decrement]


#bring it all together. Below is the non functional part. 

#in functional programming you separate the functional and the non functional parts.

from functools import reduce # reduce is in the functools library

print(reduce(call, funcs,1)) # output 7 , 2  res 124


为什么它不起作用


我改变


def call(y,f)

       f(y)



def call(f,y)

       f(y)


并给出一个错误:


................py", line 27, in call

    return f(y)


TypeError: 'int' object is not callable


一只甜甜圈
浏览 208回答 1
1回答

芜湖不芜

functools.reduce()要理解这一点,我们首先应该了解它是如何reduce工作的,reduce 需要 3 个参数:一个函数可迭代元素一个初始化器。让我们关注函数和可迭代元素来了解函数是如何调用的下面是functools的官方文档:functools.reduce(function, iterable[, initializer])将两个参数的函数从左到右累积应用于iterable的项目,以将iterable减少为单个值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 计算 ((((1+2)+3)+4)+5)。左边的参数 x 是累积值,右边的参数 y 是迭代的更新值。如果存在可选的初始值设定项,则在计算中将其放置在可迭代项之前,并在可迭代项为空时用作默认值。如果没有给出初始化程序并且可迭代只包含一个项目,则返回第一个项目。大致相当于:def reduce(function, iterable, initializer=None):     it = iter(iterable)    if initializer is None:         value = next(it)    else:         value = initializer     for element in it:         value = function(value, element)     return value在这里你可以理解,它接受第一个参数中传递的函数,并以 value、element 作为传递函数的参数来执行它。请注意,元素是 eachelement在第二个参数iterable中。所以当你打电话时reduce(call, funcs, 1),发生以下情况:由于初始化程序=1,值=初始化程序,对于 funcs 中的每个 func,发生了以下情况调用(1,函数)TLDR; 当您替换 y 和 f 时,您正在尝试调用 1(func),这是不可能的,这就是第一个初始解决方案有效的原因,因为它调用了 func(1)参考:Python Docs - functools
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python