Python converts string to variable name
I am aware that this may appear as a duplicate, but so far I have not found (or should be understood) an answer to what I am looking for.
I have a list of strings and want to convert them to a variable name, which I then assign. I understand that I might need a recorder for this, but I'm unfamiliar with them as I'm relatively new to python and all the examples I've seen so far are about values while I'm trying something else.
Im after something like:
list = ['spam', 'eggs', 'ham']
for i in range(len(list)):
list[i] = rat.readColumn(ratDataset, list[i])
where the first list [i] is a variable name, not a string. The second list [i] is a string (and for context it is the name of the Im column as read from the raster attribute table (rat))
Essentially, I want every line in the list to be given as a variable name.
The idea is that I can create a loop without having to write out a string for every variable I want, with the corresponding rat column name (string). Maybe there is a beer way to do this than I suggest?
source to share
Try the following:
lst = ['spam', 'eggs', 'ham']
d = {} # empty dictionary
for name in lst:
d[name] = rat.readColumn(ratDataset, name)
Do not use list
for your IDs as it is a type ID and you will mask its existence. The for loop can iterate directly on the elements inside - there is no need to create an index and use it on the list. d['spam']
will be one of your variables.
Although, it is also possible to create names of real variables, such as spam
, eggs
, ham
, you probably would not have done so, as the effect would have been useless.
source to share
A simple dictionary is used here:
variables = ['spam', 'eggs', 'ham']
data = {}
datum = 0
for variable in variables:
data[variable] = datum
datum+=1
print(data)
print("value : ",data[variables[2]])
This gives the result:
{'eggs': 1, 'ham': 2, 'spam': 0}
value : 2
NB: do not use list
as a variable name, list is a type identifier that can be used to convert an object to a list if possible ( list("abc")==['a', 'b', 'c']
) and you override it with the right list of values Now.
source to share
one way is to set the variable name as a string and change part or all of it using the method format()
and then use the string as a variable usingvars()[STRING]
import numpy as np
X1= np.arange(1,10)
y1=[i**2 for i in X1]
X2= np.arange(-5,5)
y2=[i**2 for i in X2]
for i in range(1,3):
X = 'X{}'.format(i)
y = 'y{}'.format(i)
print('X_{}'.format(i) , vars()[X])
print('y_{}'.format(i) , vars()[y])
Output:
X_1 [1 2 3 4 5 6 7 8 9]
y_1 [1, 4, 9, 16, 25, 36, 49, 64, 81]
X_2 [-5 -4 -3 -2 -1 0 1 2 3 4]
y_2 [25, 16, 9, 4, 1, 0, 1, 4, 9, 16]
source to share