如何评估包含等号的字符串? [英] How to eval a string containing an equal symbol?

查看:126
本文介绍了如何评估包含等号的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用eval函数时遇到了一些问题.我有一个列表,例如

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]

我该怎么做?

推荐答案

可以这样做:

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)

这篇关于如何评估包含等号的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆