Python:添加lambda定义的函数

时间:2015-05-05 18:37:21

标签: python lambda

我想知道是否有任何方法可以在函数级别添加lambda函数。

import numpy as np

f = lambda x: np.sin(5*x)+3
g = lambda x: np.cos(3*x)**2+1

x = np.linspace(-3.14,3.14,1000)
h = f+g  % is there any way to create this ?
h_of_x = h(x)

这将非常有用。

3 个答案:

答案 0 :(得分:4)

如果您正在寻找符号数学,请使用sympy

from sympy import *
x = symbols("x")
f = sin(5*x)+3
g = cos(3*x)**2+1
h = f + g

答案 1 :(得分:3)

可能是这个

h = lambda x: f(x)+g(x)

答案 2 :(得分:2)

您可以创建一个函数plus,它将两个函数作为输入并返回它们的总和:

def plus(f, g):
    def h(x):
        return f(x) + g(x)
    return h

h = plus(lambda x: x * x, lambda x: x ** 3)

示例:

>>> h(2)
12

定义plus可以带来优势,例如:

>>> f = lambda x: x * 2
>>> h = reduce(plus, [f, f, f, f]) # or h = reduce(plus, [f] * 4)
>>> h(2)
16
相关问题