如何评估包含等号的字符串?
我对 eval
函数有一些问题。例如,我有一个列表,
list1 = [('a',1), ('b',2), ('c',3)]
我想将元组的每个值分配给第一个元素:
for el in list1 :
eval(el[0]) = el[1]
我该怎么做?
I have some issues with the eval
function. I have a list like, for example,
list1 = [('a',1), ('b',2), ('c',3)]
and I would like to assign each value of a tuple to the first element:
for el in list1 :
eval(el[0]) = el[1]
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以这样做:
但是不要这么做。真的,不要。您不需要动态局部变量,您需要一个字典:
You could do this:
But don't. Really, don't. You don't need dynamic local variables, you need a dictionary:
为此,您不需要
eval
。您可以通过调用内置的
vars
直接访问本地环境。下面是一个交互式会话示例:这里
vars()
返回带有局部变量绑定的字典。由于它返回指向唯一实例(而不是副本)的指针,因此您可以就地修改它(.update
)。You don't need
eval
for that.You can access local environment directly by calling the
vars
builtin. Here's an example interactive session:Here
vars()
returns the dict with local variable bindings. Since it returns a pointer to the only instance (not a copy), you can modify it in place (.update
).