在eval()中使用(lambda)赋值时出现语法错误?

时间:2022-07-24 19:02:35

How come when I type the following

我怎么输入以下内容

eval("mult = lambda x,y: (x*y)")

I get this as an error? What's going on?

我认为这是一个错误?这是怎么回事?

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    mult = lambda x,y: (x*y)
         ^
SyntaxError: invalid syntax

What am I doing wrong? If I enter the expression as is (no eval) I get no error, and can use mult to my hearts content.

我究竟做错了什么?如果我按原样输入表达式(没有eval)我没有错误,并且可以使用mult到我心中的内容。

3 个解决方案

#1


11  

You want to use exec instead of eval. I don't know why you would want to do this though when you can just use mult = lambda x,y : (x*y)

您想使用exec而不是eval。我不知道你为什么要这样做,虽然你可以使用mult = lambda x,y:(x * y)

>>> exec("mult = lambda x,y : (x*y)")
>>> mult
<function <lambda> at 0x1004ac1b8>
>>> mult(3,6)
18

#2


8  

Eval does expressions, it doesn't assign.

Eval表达式,它不分配。

>>> eval("lambda x,y: y*x")
<function <lambda> at 0xb73c779c>
>>> eval("lambda x,y: y*x")(2, 4)
8

You must assign the eval'd expression to a variable:

您必须将eval'd表达式分配给变量:

>>> mult = eval("lambda x,y: y*x")
>>> mult(2, 3)
6

#3


2  

mult = eval("lambda x,y: (x*y)")

#1


11  

You want to use exec instead of eval. I don't know why you would want to do this though when you can just use mult = lambda x,y : (x*y)

您想使用exec而不是eval。我不知道你为什么要这样做,虽然你可以使用mult = lambda x,y:(x * y)

>>> exec("mult = lambda x,y : (x*y)")
>>> mult
<function <lambda> at 0x1004ac1b8>
>>> mult(3,6)
18

#2


8  

Eval does expressions, it doesn't assign.

Eval表达式,它不分配。

>>> eval("lambda x,y: y*x")
<function <lambda> at 0xb73c779c>
>>> eval("lambda x,y: y*x")(2, 4)
8

You must assign the eval'd expression to a variable:

您必须将eval'd表达式分配给变量:

>>> mult = eval("lambda x,y: y*x")
>>> mult(2, 3)
6

#3


2  

mult = eval("lambda x,y: (x*y)")