本文介绍了将字符串的值用作变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的字符串。

  string =someString

我现在想使用存储在字符串中的变量创建一个say(一个)()对象的新实例。我可以这样做吗?

  string = dict()

希望成为someString = dict()。这是正确的吗?如果没有,我该怎么办?还在学蟒蛇任何帮助将不胜感激。

解决方案

是的,可能被认为是一个不好的事情:

  string ='someString'
全局变量)[string] = dict()

相反,您应该执行以下操作:

  my_dynamic_vars = dict()
string ='someString'

my_dynamic_vars.update({string:dict() })

然后 my_dynamic_vars [string] 一个 dict()


Let's say I have a string like this.

string = "someString"

I now want to create a new instance of say, a dict() object using the variable stored in string. Can I do this?

string = dict()

Hoping it becomes "someString = dict()". Is this right? If not, how do i do it? Still learning python. Any help would be greatly appreciated.

解决方案

Yes, it is possible to do this, though it is considered a bad thing to do:

string = 'someString'
globals()[string] = dict()

Instead you should do something like:

my_dynamic_vars = dict()
string = 'someString'

my_dynamic_vars.update({string: dict()})

then my_dynamic_vars[string] is a dict()

这篇关于将字符串的值用作变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 18:11