条件为 x: 1/x if x!= 0 的 lambda 不起作用

lambda with condition x: 1/x if x!= 0 not work

我想用 GraphScene 绘制一个反比例函数,一切正常,但是当我设置 x != 0 的条件时,一个 SyntaxError 弹出:

f11 = self.get_graph(lambda x: 1/x if x!= 0)

SyntaxError: invalid syntax 

错误提示最后一个括号

我查了很多,lambda x: 1/x if x!= 0应该是正确的python语法,不知道为什么不行!感谢您的帮助。

图形是使用贝塞尔曲线创建的,贝塞尔曲线不能不连续,因此,您必须为要使用的每个域创建多个图形。

class AddingDomains(GraphScene):
    CONFIG = {
        "y_max" : 5,
        "y_min" : -5,
        "x_max" : 6,
        "x_min" : -6,
        "graph_origin": ORIGIN,
    }
    def construct(self):
        self.setup_axes()
        graph_left = self.get_graph(lambda x : 1/x,  
                                    color = GREEN,
                                    x_min = self.x_min, 
                                    x_max = 1/self.y_min
                                    )
        graph_right = self.get_graph(lambda x : 1/x,  
                                    color = GREEN,
                                    x_min = 1/self.y_max, 
                                    x_max = self.x_max
                                    )
        graph=VGroup(graph_left,graph_right)
        self.play(
            ShowCreation(graph),
            run_time = 2,
            rate_func= double_smooth
        )
        self.wait()

或者

class AddingDomains2(GraphScene):
    CONFIG = {
        "y_max" : 5,
        "y_min" : -5,
        "x_max" : 6,
        "x_min" : -6,
        "graph_origin": ORIGIN,
    }
    def construct(self):
        self.setup_axes()
        graph_left = self.get_graph(lambda x : 1/x,  
                                    color = GREEN,
                                    x_min = self.x_min, 
                                    x_max = 1/self.y_min
                                    )
        graph_right = self.get_graph(lambda x : 1/x,  
                                    color = GREEN,
                                    x_min = 1/self.y_max, 
                                    x_max = self.x_max
                                    )
        graph=VMobject(color=RED)
        graph.append_points(graph_left.points)
        graph.append_points(graph_right.points)
        self.play(
            ShowCreation(graph),
            run_time = 2,
            rate_func= double_smooth
        )
        self.wait()

Returns: manimlib/mobject/types/vectorized_mobject.pymanimlib/mobject/functions.py.

中的更多信息

添加一个 else 告诉 lambda 在 x==0 时应该求值什么,突然间你有了有效的语法:

lambda x: 1/x if x != 0 else 0

此语法结构是在 PEP-308, which was adopted in Python 2.5 中添加的。从PEP来看,语法变化描述如下:

test: or_test ['if' or_test 'else' test] | lambdef
or_test: and_test ('or' and_test)*
...
testlist_safe: or_test [(',' or_test)+ [',']]
...
gen_for: 'for' exprlist 'in' or_test [gen_iter]

如您所见,else是必填项;没有 一个 if 和一个 else.

就不可能有一个 test