如何评估包含等号的字符串?

发布于 2024-12-26 06:45:55 字数 218 浏览 4 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

顾北清歌寒 2025-01-02 06:45:55

可以这样做:

exec('%s = %s' % el)

但是不要这么做。真的,不要。您不需要动态局部变量,您需要一个字典:

my_dict = dict(list1)

You could do this:

exec('%s = %s' % el)

But don't. Really, don't. You don't need dynamic local variables, you need a dictionary:

my_dict = dict(list1)
浪漫人生路 2025-01-02 06:45:55

为此,您不需要 eval

您可以通过调用内置的 vars 直接访问本地环境。下面是一个交互式会话示例:

>>> list1 = [("a", 4), ("b", 8)]
>>> vars().update(dict(list1))
>>> a
4
>>> b
8

这里 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:

>>> list1 = [("a", 4), ("b", 8)]
>>> vars().update(dict(list1))
>>> a
4
>>> b
8

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文