如何在Python中将函数作为函数参数传递 [英] How to pass a function as a function parameter in Python
问题描述
这是我目前拥有的,并且工作正常:
This is what I currently have and it works fine:
def iterate(seed, num):
x = seed
orbit = [x]
for i in range(num):
x = 2 * x * (1 - x)
orbit.append(x)
return orbit
现在,如果我想将第5行的迭代方程式更改为x = x ** 2-3,则必须使用第5行以外的所有相同代码创建一个新函数.可以将函数用作参数的更通用的函数?
Now if I want to change the iterating equation on line 5 to, say, x = x ** 2 - 3, I'll have to create a new function with all the same code except line 5. How do I create a more general function that can have a function as a parameter?
推荐答案
功能是一等公民在Python.您可以将函数作为参数传递:
Functions are first-class citizens in Python. you can pass a function as a parameter:
def iterate(seed, num, fct):
# ^^^
x = seed
orbit = [x]
for i in range(num):
x = fct(x)
# ^^^
orbit.append(x)
return orbit
在您的代码中,您将传递所需的函数作为第三个参数:
In your code, you will pass the function you need as the third argument:
def f(x):
return 2*x*(1-x)
iterate(seed, num, f)
# ^
或
def g(x):
return 3*x*(2-x)
iterate(seed, num, g)
# ^
或者...
如果您不想每次都命名一个新函数,则可以选择传递一个匿名函数(即: lambda ):
If you don't want to name a new function each time, you will have the option to pass an anonymous function (i.e.: lambda) instead:
iterate(seed, num, lambda x: 3*x*(4-x))
这篇关于如何在Python中将函数作为函数参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!