简体   繁体   中英

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 :

y = [feature1, feature2]

How can I do that in Python?

One could directly put the variables into globals :

x = ['feature1','feature2']

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

print(feature1)
# 123

This will allow creating y as specified in the question.

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. 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 . 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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