在 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
芜湖不芜
相关分类