151

我有任何字符串。像“水牛”,

x='buffalo'

我想将此字符串转换为一些变量名,例如,

buffalo=4 

不仅是这个例子,我想将任何输入字符串转换为一些变量名。我应该怎么做(在python中)?

4

3 回答 3

171
x='buffalo'    
exec("%s = %d" % (x,2))

之后,您可以通过以下方式进行检查:

print buffalo

作为输出,您将看到: 2

于 2013-10-01T17:39:14.760 回答
44

这是最好的方法,我知道在 python 中创建动态变量。

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

我在这里找到了一个类似但不相同的问题 从用户输入创建动态命名变量

于 2013-10-01T17:30:22.100 回答
22

您可以使用字典来跟踪键和值。

例如...

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.

字典与现实生活中的字典非常相似。你有一个词,你有一个定义。您可以查找单词并获得定义。所以在这种情况下,你有“Buffalo”这个词,它的定义是 4。它可以与任何其他词和定义一起使用。只要确保先将它们放入字典即可。

于 2013-10-01T17:36:09.030 回答