Har*_*ana 90 python python-2.7
我有任何字符串.像'水牛',
x='buffalo'
Run Code Online (Sandbox Code Playgroud)
我想将此字符串转换为某个变量名称,如
buffalo=4
Run Code Online (Sandbox Code Playgroud)
不仅这个例子,我想将任何输入字符串转换为某个变量名.我该怎么做(在python中)?
Ste*_*anW 104
x='buffalo'
exec("%s = %d" % (x,2))
Run Code Online (Sandbox Code Playgroud)
之后你可以通过以下方式检查:
print buffalo
Run Code Online (Sandbox Code Playgroud)
作为输出,您将看到:
2
phn*_*sin 24
这是最好的方法,我知道在python中创建动态变量.
my_dict = {}
x = "Buffalo"
my_dict[x] = 4
Run Code Online (Sandbox Code Playgroud)
我在这里找到了一个类似但不一样的问题. 从用户输入创建动态命名变量
[根据Martijn的建议编辑]
Dea*_*hex 15
您可以使用词典来跟踪键和值.
例如...
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.
Run Code Online (Sandbox Code Playgroud)
字典非常类似于现实生活字典.你有一个词,你有一个定义.你可以查找单词并获得定义.所以在这种情况下,你有"Buffalo"这个词,它的定义是4.它可以与任何其他单词和定义一起使用.只需确保先将它们放入字典中.
| 归档时间: |
|
| 查看次数: |
215878 次 |
| 最近记录: |