pretty basic: get variable name from list of strings?
Benji
me at somewhere.com
Mon Jul 29 19:38:34 EDT 2002
chris wrote:
> in the specific,
>
> if I have a list
>
> animals = ['horse_0', 'horse_1']
> horsenames = ['smokey', 'silver']
>
> how do assign variables with those strings as names?
>
> ie, I want
> horse_0 = "smokey"
> horse_1= "silver"
>
> but if I write animals[0] = "smokey", it replaces the value, it
> doesn't assign it. What I want is like assign() or eval() in other
> languages.
>
> you can imagine i am trying to iterate over large indexes of
> animals[i] = 'horse_' + str(i)
> and then assign them from a value list
>
> or even screw the variable list and instead iterate over the
> value list
> 'horse_' + str(i) = horsenames[i].
>
> but i'm missing the key command to tell python "treat this string like
> code and not a string."
>
> thx,
> chris
As Andrew pointed out, you probably would be better off using a dict,
but if you must use variables, you could use the "globals" and "vars"
builtin functions which both return a dict of objects and variables
respectiveley.
I'm not sure how they differ, but "vars" may return the dict of
variables from the local namespace... ie: if you're in a function,
"vars" may return the local variables while globals returns the global
variables. This is just a guess though, anywy, here's how you could do it:
vars()['horse_' + str(i)] = horsenames[i]
or
globals()['horse_' + str(i)] = horsenames[i]
Again though, you should look into using a dict =),
benji
More information about the Python-list
mailing list