Reputation: 3938
I am trying to do the following in python: I have a list which contains some string values. The list looks like this:
parameters = ['RH', 'WindSp_Avg', 'WindDir']
What I want to do - and I really hope the question is not ridiculous - is to create three lists which each of them have the name of the "parameters" list. For example:
RH = []
WindSp_Avg = []
WindDir = []
I am new in python and although I had searched a bit online I couldn't find some elegant way to do something like this.
I am trying something like this:
for i in parameters:
parameters[0] = []
But it doesn't seem to work. Any suggestions?
Thanks Dimitris
Upvotes: 1
Views: 1303
Reputation: 927
parameters = ['RH', 'WindSp_Avg', 'WindDir']
for i in parameters:
vars()[i] = [];
print locals()
Upvotes: 1
Reputation: 2754
you could something like this:
code = "{0} = []"
for i in parameters:
codeobj = compile(code.format(i), "/dev/null", "single")
eval(codeobj)
but i think tha's very unsafe. Because it could be something in parameters and that will be excuted by the eval. So please only use this if it's only really necessary and security is less important.
Upvotes: 0
Reputation: 51
To create a variable you can do so:
parameters = ['RH', 'WindSp_Avg', 'WindDir']
for i in parameters:
exec("%s = []" % i);
print vars()
Upvotes: 0
Reputation: 56467
What you are trying to do is very unsafe and is against all good practices. Is there a problem in simply creating a dictionary?
myVars = {}
for param in parameters:
myVars[param] = []
WARNING The following code is for educational purposes! DO NOT USE IT IN REAL CODE!
You can do a hard hack to add dynamically a variable to the local variables inside a function. Normally locals()
represent all local variables. However simply adding to that dictionary won't solve the problem. There is a hack to force Python to reevaluate locals by using exec
, for example:
def test():
for param im parameters:
locals()[param] = []
exec ""
print WindSp_Avg
and result:
>>> test()
[]
Upvotes: 9