用Python for循环更改变量名称 [英] Changing variable names with Python for loops

查看:1193
本文介绍了用Python for循环更改变量名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 <$ c $ 

(3)
group + i = self.getGroup(selected,header + i)

,以便变量的名称改变以适应数据。谢谢!



〜Sam

解决方案

单独的变量。例如

  d = {} 
在范围内(3):
d [group + str(i)] = self.getGroup(selected,header + i)

如果你坚持实际上修改局部变量,你可以使用 locals 函数:

  for我在范围(3):
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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆