为简单起见,我试着这样做。
spam = [1,2,3]
stuff = [spam]
x = input()
if x in stuff:
print(True)
else:
print(False)
运行时:
>>> spam
False
当然它不会打印'True',因为字符串'spam'不等于变量spam。
是否有一种简单的编码方式可以检查输入是否等于变量名?如果不简单,什么?
答案 0 :(得分:1)
>>> spam= [1,2,3]
>>> stuff = [spam]
>>> eval('spam') in stuff
True
免责声明:在您自己risk处执行此操作。
答案 1 :(得分:1)
您应该检查变量的locals()
和globals()
词典。这些词典具有变量名称作为键及其值。
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)
答案 2 :(得分:0)
尝试将变量名称与程序外的世界连接起来是一个奇怪的想法。怎么样:
data = {'spam':[1,2,3]}
stuff = [data['spam']]
x = raw_input()
if data[x] in stuff:
print(True)
else:
print(False)
答案 3 :(得分:0)
最好不要使用:
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