使用字符串变量作为变量名 [英] Using a string variable as a variable name
本文介绍了使用字符串变量作为变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何在 Python 中实现变量变量?
我有一个分配给它的字符串的变量,我想根据该字符串定义一个新变量.
foo = "bar"foo = "别的东西"#我真正想要的是:bar = "别的东西"
解决方案
您可以使用 exec
:
Possible Duplicate:
How do I do variable variables in Python?
I have a variable with a string assigned to it and I want to define a new variable based on that string.
foo = "bar"
foo = "something else"
# What I actually want is:
bar = "something else"
解决方案
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
这篇关于使用字符串变量作为变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文