Best way to generate alternate toggling values in a loop?

Paul Hankin paul.hankin at gmail.com
Thu Oct 18 13:47:27 CEST 2007


On Oct 18, 12:11 pm, "Amit Khemka" <khemkaa... at gmail.com> wrote:
> On 10/18/07, Carsten Haese <cars... at uniqsys.com> wrote:
> > 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))

I like this code: straightforward and pragmatic. Everyone else seems
to be reinventing itertools.cycle - they should have listened to
Carsten, and written something like this:

import itertools

clvalues = itertools.cycle(['Even', 'Odd'])
for clvalue, (id, name) in itertools.izip(clvalues, result):
     stringBuffer.write('''
     <tr class="%(name)s">
            <td>%(id)d</td>
            <td>%(clvalue)s</td>
     </tr>''' % locals())

--
Paul Hankin




More information about the Python-list mailing list