Best way to generate alternate toggling values in a loop?

Gerard Flanagan grflanagan at yahoo.co.uk
Thu Oct 18 09:43:45 CEST 2007


On Oct 18, 1:55 am, Debajit Adhikary <debaj... at gmail.com> 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?
>


from itertools import izip

def toggle(start=True):
    flag = start
    while 1:
        flag = not flag
        yield flag


CSS = ("even", "odd")

HTML = '<tr class="%s"><td>%d</td><td>%s</td></tr>'

result = [(1, 'One'), (2, 'two'), (3, 'Three'), (4, 'Four'), (5,
'Five')]

for flag, (id, name) in izip(toggle(), result):
    print HTML % (CSS[flag], id, name)


<tr class="even"><td>1</td><td>One</td></tr>
<tr class="odd"><td>2</td><td>two</td></tr>
<tr class="even"><td>3</td><td>Three</td></tr>
<tr class="odd"><td>4</td><td>Four</td></tr>
<tr class="even"><td>5</td><td>Five</td></tr>




More information about the Python-list mailing list