使用 Python for 循环更改变量名 [英] Changing variable names with Python for loops
问题描述
我只是想知道是否有人知道一种基于 for 循环更改变量名称的方法:
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!
~山姆
推荐答案
您可能需要一个 dict 而不是单独的变量.例如
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)
如果你坚持实际修改局部变量,你可以使用locals
函数:
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)
另一方面,如果你真正想要的是修改你所在类的实例变量,那么你可以使用setattr
函数
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屋!