views:

205

answers:

4

Hi, I was trying to simplify the code:

            header = []
            header.append(header1)
            header.append(header2)                
            header.append(header3)
            header.append(header4)
            header.append(header5)
            header.append(header6)

where:

            header1 = str(input.headerOut1)
            header2 = str(input.headerOut2)
            header3 = str(input.headerOut3)
            header4 = str(input.headerOut4)
            header5 = str(input.headerOut5)
            header6 = str(input.headerOut6)

I had wanted to use a for loop, like:

   headerList = []
   for i in range(6)
          headerList.append(header+i)

however, python won't recognize that header+i represents the string header1. Is there any way to simplify this code or get the for loop to work? Thank you so much!

+2  A: 

Put the headers in an array and loop through it.

Peter
+2  A: 

You can use locals to get the the local scope as a dict:

headerList = []
for i in xrange(1, 7):
    headerList.append(locals()['header%s' % (i,)])

If possible, though, you should just use the input variable directly, as some of the other answers suggested.

Noah Medling
I just had a quick question about this, i have never seen the % (i,) before. What exactly does it do? Thanks!
It's the string formatting operator. Check out the docs here: http://www.python.org/doc/lib/typesseq-strings.html
Noah Medling
great, thank you so much!
+6  A: 
header = [str(getattr(input, "headerOut%d" % x)) for x in range(1,7)]
Roger Pate
+10  A: 

You should really structure your data as a list or a dictionary, like this:

input.headerOut[1]
input.headerOut[2]
# etc.

which would make this a lot easier, and more Pythonic. But you can do what you want using getattr:

headerList = []
for i in range(1, 7):
    header = str(getattr(input, 'headerOut%d' % i))
    headerList.append(header)
RichieHindle
...and if using a list, the first one would be input.headerOut[0].
Laurence Gonsalves
+1 for The Right Thing To Do
John Pirie
agree with @JohnPirie, +1 as there many novel answers but only one that yields code that's easy to understand.
Mark Roddy