Best way to generate alternate toggling values in a loop?

Amit Khemka khemkaamit at gmail.com
Thu Oct 18 07:11:48 EDT 2007


On 10/18/07, Carsten Haese <carsten at uniqsys.com> wrote:
> On Wed, 2007-10-17 at 23:55 +0000, Debajit Adhikary wrote:
> > I'm writing this little Python program which will pull values from a
> > database and generate some XHTML.
> >
> > I'm generating a <table> where I would like the alternate <tr>'s to be
> >
> > <tr class="Even">
> > and
> > <tr class="Odd">
> >
> > What is the best way to do this?
> >
> > I wrote a little generator (code snippet follows). Is there a better
> > (more "Pythonic") way to do this?
> >
> >
> > # Start of Code
> >
> > def evenOdd():
> >     values = ["Even", "Odd"]
> >     state = 0
> >     while True:
> >         yield values[state]
> >         state = (state + 1) % 2
> >
> >
> > # Snippet
> >
> >     trClass = evenOdd()
> >     stringBuffer = cStringIO.StringIO()
> >
> >     for id, name in result:
> >         stringBuffer.write('''
> >         <tr class="%s">
> >             <td>%d</td>
> >             <td>%s</td>
> >         </tr>
> >         '''
> >         %
> >         (trClass.next(), id, name))
>
> This is a respectable first attempt, but I recommend you familiarize
> yourself with the itertools module. It has lots of useful tools for
> making your code more elegant and concise.
>
> Rather than spelling out the final result, I'll give you hints: Look at
> itertools.cycle and itertools.izip.
>

Why not just use enumerate ?

clvalues = ["Even", "Odd"]
for i, (id, name) in enumerate(result):
    stringBuffer.write('''
    <tr class="%s">
           <td>%d</td>
           <td>%s</td>
     </tr>
     '''
    %
    (clvalues[i % 2], id, name))

Cheers,

-- 
--
Amit Khemka



More information about the Python-list mailing list