我正在搜索如何以类似sympy的方式定义表达式对于x <0为f(x)= x,对于x> 0为x ** 2 + 2我尝试过没有成功的类似理解列表谢谢
您所描述的称为分段函数:
In [1]: p = Piecewise((x, x<0), (x**2 + 2, x>0))
In [2]: p
Out[2]:
⎧ x for x < 0
⎪
⎨ 2
⎪x + 2 for x > 0
⎩
https://docs.sympy.org/latest/modules/functions/elementary.html#sympy-functions-elementary-piecewise