views:

1054

answers:

4

Hi, 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

+2  A: 

It looks like you want to use a list instead:

group=[]
for i in range(3):
     group[i]=self.getGroup(selected, header+i)
Greg Hewgill
Do you mean "Dictionary" or "List"? What's an Array?
S.Lott
I mean List, thanks. I've called ordered collections of items "arrays" for a very long time, and have never used PHP where they usurped the term to mean "associative array".
Greg Hewgill
+14  A: 

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)]
Eli Courtwright
A: 

You could access your class's __dict__ attribute:

for i in range(3)
     self.__dict__['group%d' % i]=self.getGroup(selected, header+i)

But why can't you just use an array named group?

eduffy
Instead of using self.__dict__[etc] you'll want to use setattr(self, etc), and I'm sure you meant to say 'list' instead of 'array'. Good use of string formatting though.
tgray
+3  A: 

Use a list.

groups = [0]*3
for i in xrange(3):
    groups[i] = self.getGroup(selected, header + i)

or more "Pythonically":

groups = [self.getGroup(selected, header + i) for i in xrange(3)]

For what it's worth, you could try to create variables the "wrong" way, i.e. by modifying the dictionary which holds their values:

l = locals()
for i in xrange(3):
    l['group' + str(i)] = self.getGroup(selected, header + i)

but that's really bad form, and possibly not even guaranteed to work.

David Zaslavsky