简体   繁体   English

如何在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

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?现在,如果我想将第 5 行的迭代方程更改为 x = x ** 2 - 3,我将不得不使用除第 5 行之外的所有相同代码创建一个新函数。如何创建一个更通用的函数可以将函数作为参数的函数?

Functions are first-class citizens in Python.函数是 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)
#                  ^

Or或者

def g(x):
    return 3*x*(2-x)

iterate(seed, num, g)
#                  ^

Or ...或者 ...


If you don't want to name a new function each time, you will have the option to pass an anonymous function (ie: lambda ) instead:如果您不想每次都命名一个新函数,您可以选择传递一个匿名函数(即: lambda ):

iterate(seed, num, lambda x: 3*x*(4-x))

Just pass the function as a parameter.只需将函数作为参数传递即可。 For instance:例如:

def iterate(seed, num, func=lambda x: 2*x*(1-x)):
    x = seed
    orbit = [x]
    for i in range(num):
        x = func(x)
        orbit.append(x)
    return orbit

You can then either use it as you currently do or pass a function (that takes a single argument) eg:然后,您可以像当前一样使用它,也可以传递一个函数(采用单个参数),例如:

iterate(3, 12, lambda x: x**2-3)

You can also pass existing (non lambda functions) in the same way:您还可以以相同的方式传递现有(非 lambda 函数):

def newFunc(x):
    return x**2 - 3

iterate(3, 12, newFunc)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM