用Python for循环更改变量名称 [英] Changing variable names with Python for loops
问题描述
<$ c $(3)
group + i = self.getGroup(selected,header + i)
,以便变量的名称改变以适应数据。谢谢!
〜Sam
单独的变量。例如
d = {}
在范围内(3):
d [group + str(i)] = self.getGroup(selected,header + i)
如果你坚持实际上修改局部变量,你可以使用 locals
函数:
for我在范围(3):
$ p另一方面,如果你真正想要的是修改你所在类的实例变量,那么你可以使用
locals()[group+ str(i)] = self.getGroup(selected,header + i)
setattr $ b
/ code> function
对于组(3)中的我:
setattr(self,group + str(i),self.getGroup(selected,header + i)
当然,我假设所有这些例子,你不只是想要一个列表:
$ $ p $groups = [self.getGroup(i ,header + i)for i in range(3)]
I was just wondering if anyone knew of a way to change variable names based off of a for loop for something like this:
for i in range(3)
group+i=self.getGroup(selected, header+i)
so that the names of the variables change to accomodate the data. Thanks!
~Sam
You probably want a dict instead of separate variables. For example
d = {}
for i in range(3):
d["group" + str(i)] = self.getGroup(selected, header+i)
If you insist on actually modifying local variables, you could use the locals
function:
for i in range(3):
locals()["group"+str(i)] = self.getGroup(selected, header+i)
On the other hand, if what you actually want is to modify instance variables of the class you're in, then you can use the setattr
function
for i in group(3):
setattr(self, "group"+str(i), self.getGroup(selected, header+i)
And of course, I'm assuming with all of these examples that you don't just want a list:
groups = [self.getGroup(i,header+i) for i in range(3)]
这篇关于用Python for循环更改变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!