将字符串转换为变量名称我有绳子。就像“水牛”x='buffalo'我想把这个字符串转换成一些变量名,buffalo=4不仅仅是这个例子,我希望将任何输入字符串转换为某个变量名。我应该怎么做(在python中)?
3 回答

喵喵时光机
TA贡献1846条经验 获得超7个赞
x='buffalo' exec("%s = %d" % (x,2))
print buffalo
2

互换的青春
TA贡献1797条经验 获得超6个赞

慕莱坞森
TA贡献1810条经验 获得超4个赞
您可以使用字典来跟踪键和值。
比如说.。
dictOfStuff = {} ##Make a Dictionary
x = "Buffalo" ##OR it can equal the input of something, up to you.
dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to what ever you like
print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.
字典和现实生活的字典非常相似。你有一个词,你有一个定义。你可以查找单词并得到定义。所以在这个例子中,你有“水牛”这个词,它的定义是4,它可以和任何其他的词和定义一起工作。先把它们放在字典里就行了。
添加回答
举报
0/150
提交
取消