如何在python中使用eval分配变量的值? [英] How can I assign the value of a variable using eval in python?
问题描述
好的.所以我的问题很简单:如何在 Python 中使用 eval 分配变量的值?我试过 eval('x = 1')
但这不起作用.它返回一个语法错误.为什么这行不通?
因为 x=1
是一个语句,而不是一个表达式.使用 exec
运行语句.><预><代码>>>>exec('x=1')>>>X1
<小时>
顺便说一句,如果您只需要一个动态名称来分配,有很多方法可以避免使用 exec
/eval
,例如你可以使用字典,setattr
函数、或:locals()
字典
更新:虽然上面的代码在 REPL 中有效,但它在函数中不起作用.如果 exec
不可用,请参阅 在 Python 中修改本地变量 以了解一些替代方法问题.
Okay. So my question is simple: How can I assign the value of a variable using eval in Python? I tried eval('x = 1')
but that won't work. It returns a SyntaxError. Why won't this work?
Because x=1
is a statement, not an expression. Use exec
to run statements.
>>> exec('x=1')
>>> x
1
By the way, there are many ways to avoid using exec
/eval
if all you need is a dynamic name to assign, e.g. you could use a dictionary, the setattr
function, or the :locals()
dictionary
>>> locals()['y'] = 1
>>> y
1
Update: Although the code above works in the REPL, it won't work inside a function. See Modifying locals in Python for some alternatives if exec
is out of question.
这篇关于如何在python中使用eval分配变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!