programmatically define a new variable on the fly
DustanGroups at gmail.com
Fri Aug 10 00:30:08 CEST 2007
On Aug 9, 5:11 pm, Lee Sander <lesa... at gmail.com> wrote:
> I would like to define a new variable which is not predefined by me.
> For example,
> I want to create an array called "X%s" where "%s" is to be determined
> based on the data I am processing. So, for example, if I the file
> I'm reading has
> g 99
> on the first line, I want to create a new variable called "Xg" whose
> is 99.
> I tried eval("Xg=*99") but that did not work.
eval only evaluates expressions. To go about the problem that way, you
would use exec, not eval.
Of course, use of exec generally means you're going about the problem
the wrong way; it looks to me like a better way to do what you're
doing is to create a dictionary to hold your values. So, given the
variables data (the dictionary), name (in your example, 'g') and
*size* (in your example, 99), you can add it data as shown:
data[name] = 
data[name] *= size
Note that by splitting the '*size' code into two lines as shown
above, you don't create an intermediate list object that gets thrown
away right after creation.
More information about the Python-list