1

I declare a variable, say:

var=33

I want to assign to another variable the string 'var', that is , how to get the symbol's name of the value of the variable.

How can I do it ?


I reformulate the question.

WHITE=0
RED=1
BLACK=2

X=2.

I want to assign the value 'BLACK' to a variable, say, Y, taking into account that X=2.

It is hard to formulate exactly this question.

I want to avoid a code like this:

color=''
if X==0:
     color='WHITE'
elif X==1:
etc.

Is it possible to get the name of the color-variable as a string?

4

3 回答 3

7

I want to assign to another variable the string 'var', that is , how to get the symbol's name of a variable.

No, you don't want to do that. Use a dict:

mydata = {}
varname = 'var'
mydata[varname] = 33

Technically, you could use the dict from globals() or locals() to store this, and it would be available as a "real variable", but really, there's no good reason to do that, it will make your code much more difficult to understand.

The way to avoid the code you give:

color=''
if X==0:
     color='WHITE'
elif X==1:
etc.

Is with:

COLORS = ('WHITE', 'RED', 'BLACK')
x = 2
try:
    color = COLORS[x]
except IndexError:
    color = 'DEFAULT COLOR'

This eliminates sequential ifs, and maintenance beyond expanding COLORS. You could also do:

COLORS = {0: 'WHITE', 1: 'RED', 2: 'BLACK'}
x = 2
color = COLORS.get(x, 'DEFAULT COLOR')

But that requires manual management of the indices (keys) also.

于 2012-07-19T22:25:22.743 回答
3
colors = {0:"WHITE", 1:"RED", 2:"BLACK"}
X=2
print colors[X]
于 2012-07-19T22:40:03.937 回答
1

If you absolutely, positively, MUST have it:

x = 2
n = locals()
n['x'] # 2
于 2012-07-19T22:45:19.073 回答