在python中将字符串转换为变量名[重复]
- 2024-12-17 08:31:00
- admin 原创
- 147
问题描述:
我有任何字符串。例如“buffalo”,
x='buffalo'
我想将此字符串转换为一些变量名,例如,
buffalo=4
不仅是这个例子,我想将任何输入字符串转换为某个变量名。我应该怎么做(在 Python 中)?
解决方案 1:
x='buffalo'
exec("%s = %d" % (x,2))
之后您可以通过以下方式检查:
print buffalo
您将看到以下输出:2
解决方案 2:
这是我所知道的在 python 中创建动态变量的最佳方法。
my_dict = {}
x = "Buffalo"
my_dict[x] = 4
我在这里发现了类似但不相同的问题,
从用户输入创建动态命名变量
解决方案 3:
您可以使用字典来跟踪键和值。
例如...
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。它可以与任何其他单词和定义一起使用。只要确保你先把它们放进字典里就行了。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD