如何在Python中使用字符串检查变量名?

How to check for a variable name using a string in Python?

为了简单起见,我试着这么做。

1
2
3
4
5
6
7
spam = [1,2,3]
stuff = [spam]
x = input()
if x in stuff:
    print(True)
else:
    print(False)

运行时:

1
2
>>> spam
False

当然,它不打印"true",因为字符串"spam"不等于变量spam。

是否有一种简单的编码方法可以检查输入是否等于变量名?如果不简单,有什么?


您应该检查locals()globals()字典中的变量。这些字典有变量名作为键及其值。

1
2
3
4
5
6
7
8
9
10
spam = [1,2,3]
stuff = [spam]

x = raw_input()

if x in locals() and (locals()[x] in stuff) or \
   x in globals() and (globals()[x] in stuff):
    print(True)
else:
    print(False)

您可以阅读更多关于locals()globals()的内容。


1
2
3
4
>>> spam= [1,2,3]
>>> stuff = [spam]
>>> eval('spam') in stuff
True

DISCLAIMER : do this at your own risk.


最好使用:

1
2
3
4
data = {'spam':[1,2,3]} #create dictionary with key:value
x = input() # get input
print(x in data) #print is key in dictionary (True/False) you might use:
#print(str(x in data)) #- this will convert boolean type name to string value


尝试将变量名与程序外部的世界连接起来是一个奇怪的想法。怎么样:

1
2
3
4
5
6
7
8
9
data = {'spam':[1,2,3]}

stuff = [data['spam']]

x = raw_input()
if data[x] in stuff:
    print(True)
else:
    print(False)