【发布时间】:2020-04-27 11:12:03
【问题描述】:
在 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
【问题讨论】:
-
它是否与
def call(f,y):f(y)一起工作?,调用reduce的方式,在你的函数call你的第一个参数应该是函数,第二个应该是int。 -
为什么预期的输出是
7 , 2 res 124??
标签: python python-3.x function arguments