Best way to generate alternate toggling values in a loop?

Carsten Haese carsten at uniqsys.com
Wed Oct 17 20:19:36 EDT 2007


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.
 
HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list