一只羔羊里面的Python

2024-05-20 17:58:45 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么left = lambda: cursor = cursor - 1工作而left = lambda: cursor -= cursor给我一个语法错误?你知道吗

lambda中就地减法有问题吗?你知道吗

编辑: 一点背景。 我正在尝试与一个成员一起上课,例如:

self.instructions = {
            "0": lambda: self.tape[self.cursor] = 0   
            "1": lambda: self.tape[self.cursor] = 1
            "L": lambda: self.cursor -= 1
            "R": lambda: self.cursor += 1
            "HALT" = lambda: self.halted = True]
        }

我该怎么做?你知道吗


Tags: lambdaselftrue编辑成员leftcursor背景
3条回答

lambda表达式是只返回值的函数的快捷方式:

func = lambda x: x - 1

大致与

def func(x):
    return x - 1

您的两个示例都不起作用,因为赋值在Python中并不像在其他一些语言(特别是类似于C的语言)中那样是一个表达式。也就是说,cursor = cursor - 1不能像cursor -= 1一样位于lambda中。两者都不能放在return语句中。你知道吗

您使用的lambda表达式语法错误。看看这个例子:

>>> decrement = lambda x: x - 1
>>> decrement(24)
23

直截了当的解决方案:

def zero(self):
    self.tape[self.cursor] = 0

def one(self):
    self.tape[self.cursor] = 1

def left(self):
    self.cursor -= 1

def right(self):
    self.cursor += 1

def halt(self):
    self.halted = True

self.instructions = {
        "0": self.zero(),  
        "1": self.one(),
        "L": self.left(),
        "R": self.right(),
        "HALT": self.halt()
        }

不是最好的设计,但它应该工作。你知道吗

相关问题 更多 >