How to eval a string containing an equal symbol?

≯℡__Kan透↙ 提交于 2020-01-04 12:37:25

问题


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?


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/8818318/how-to-eval-a-string-containing-an-equal-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!