How to pass a function as a function parameter in Python

后端 未结 2 1812
无人共我
无人共我 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:15

    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:

    def newFunc(x):
        return x**2 - 3
    
    iterate(3, 12, newFunc)
    

提交回复
热议问题