简体   繁体   English

如何在python中将字符串转换为变量名

[英]How to convert a string to a variable name in python

I have a list of two strings:我有两个字符串的列表:

x = ['feature1','feature2']

I need to create the following list y from the list x :我需要从列表x创建以下列表y

y = [feature1, feature2]

How can I do that in Python?我怎样才能在 Python 中做到这一点?

One could directly put the variables into globals :可以直接将变量放入globals

x = ['feature1','feature2']

for varname in x:
    globals()[varname] = 123

print(feature1)
# 123

This will allow creating y as specified in the question.这将允许创建问题中指定的y

The fact that it's possible, however, doesn't indicate that it should be done this way.然而,它是可能的事实并不表明它应该以这种方式完成。 Without knowing specifics of the problem you are solving, it's difficult to advise further, but there might be a better way to achieve what you are after.在不了解您正在解决的问题的具体细节的情况下,很难提供进一步的建议,但可能有更好的方法来实现您所追求的目标。

Update: in a comment @mozway raised some concerns with the above, one of which was that y will not be modified if, for example, feature2 is modified.更新:@mozway 在评论中对上述内容提出了一些担忧,其中之一是y不会被修改,例如,如果 feature2 被修改。 For example:例如:

x = ['feature1','feature2']

for varname in x:
    globals()[varname] = 123

y = [feature1, feature2]
print(y)
# [123, 123]

feature2 = 456
print(y)
# [123, 123]

This seems like a useful thing to keep in mind, albeit even with regular syntax I get a similar behaviour:记住这似乎是一件有用的事情,尽管即使使用常规语法,我也会得到类似的行为:

feature1 = 123
feature2 = 123
y = [feature1, feature2]
print(y)
# [123, 123]

feature2 = 456
print(y)
# [123, 123]

Just for syntactical purposes here a possibility with exec .仅出于语法目的,这里有exec的可能性。 Remember that it accepts extra parameters to restrict the scope of the variables (default is global).请记住,它接受额外的参数来限制变量的范围(默认为全局)。

x = ['feature1','feature2']

for s in x:
    exec(f'{s} = "{s}"') # execute the string containing a python command

y = [feature1, feature2]
print(y)
#['feature1', 'feature2']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM