How to pass a function as a function parameter in Python

后端 未结 2 1830
无人共我
无人共我 2021-01-12 11:46

This is what I currently have and it works fine:

def iterate(seed, num):
    x = seed
    orbit = [x]
    for i in ran         


        
2条回答
  •  误落风尘
    2021-01-12 12:26

    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)
    #                  ^
    

    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 (i.e.: lambda) instead:

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

提交回复
热议问题