473,288 Members | 1,726 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,288 software developers and data experts.

Best way to generate alternate toggling values in a loop?

I'm writing this little Python program which will pull values from a
database and generate some XHTML.

I'm generating a <tablewhere 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))
# End of Code

Oct 18 '07 #1
10 3488
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 <tablewhere 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
Oct 18 '07 #2
On 2007-10-17, Debajit Adhikary <de******@gmail.comwrote:
# Start of Code

def evenOdd():
values = ["Even", "Odd"]
state = 0
while True:
yield values[state]
state = (state + 1) % 2
I'd replace the last line with

state ^= 1

to save a couple instructions, but I spend too much time
working with micoroprocessors running on clocks measured in the
KHz.

There are probably other more Pythonic ways...

--
Grant Edwards grante Yow! My EARS are GONE!!
at
visi.com
Oct 18 '07 #3
On Oct 18, 1:55 am, Debajit Adhikary <debaj...@gmail.comwrote:
I'm writing this little Python program which will pull values from a
database and generate some XHTML.

I'm generating a <tablewhere 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>

Oct 18 '07 #4
On 10/18/07, Carsten Haese <ca*****@uniqsys.comwrote:
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 <tablewhere 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
Oct 18 '07 #5
On Oct 18, 12:11 pm, "Amit Khemka" <khemkaa...@gmail.comwrote:
On 10/18/07, Carsten Haese <cars...@uniqsys.comwrote:
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

Oct 18 '07 #6
On 2007-10-18, Gerard Flanagan <gr********@yahoo.co.ukwrote:
On Oct 18, 1:55 am, Debajit Adhikary <debaj...@gmail.comwrote:
>I'm writing this little Python program which will pull values from a
database and generate some XHTML.

I'm generating a <tablewhere 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
I like the solution somebody sent me via PM:

def toggle():
while 1:
yield "Even"
yield "Odd"

--
Grant Edwards grante Yow! Are we THERE yet?
at
visi.com
Oct 18 '07 #7
Grant Edwards <gr****@visi.comwrote:
...
I like the solution somebody sent me via PM:

def toggle():
while 1:
yield "Even"
yield "Odd"
I think the itertools-based solution is more elegant:

toggle = itertools.cycle(('Even', 'Odd'))

and use toggle rather than toggle() later; or, just use that
itertools.cycle call inside the expression instead of toggle().
Alex

Oct 18 '07 #8
On Oct 18, 2:29 am, Grant Edwards <gra...@visi.comwrote:
On 2007-10-17, Debajit Adhikary <debaj...@gmail.comwrote:
# Start of Code
def evenOdd():
values = ["Even", "Odd"]
state = 0
while True:
yield values[state]
state = (state + 1) % 2

I'd replace the last line with

state ^= 1

to save a couple instructions, but I spend too much time
working with micoroprocessors running on clocks measured in the
KHz.

There are probably other more Pythonic ways...

I always use:

state = 1 - state

for toggles. I doubt it's much more pythonic though :)

Iain

Oct 18 '07 #9
On Oct 18, 3:48 pm, Iain King <iaink...@gmail.comwrote:
On Oct 18, 2:29 am, Grant Edwards <gra...@visi.comwrote:
On 2007-10-17, Debajit Adhikary <debaj...@gmail.comwrote:
# Start of Code
def evenOdd():
values = ["Even", "Odd"]
state = 0
while True:
yield values[state]
state = (state + 1) % 2
I'd replace the last line with
state ^= 1
to save a couple instructions, but I spend too much time
working with micoroprocessors running on clocks measured in the
KHz.
There are probably other more Pythonic ways...

I always use:

state = 1 - state

for toggles. I doubt it's much more pythonic though :)

Iain
why not do
state = not state
?

Oct 18 '07 #10
On Thursday 18 October 2007 09:09, Grant Edwards wrote:
I like the solution somebody sent me via PM:

def toggle():
while 1:
yield "Even"
yield "Odd"
That was me.
Sorry, list, I meant to send it to everyone but I my webmail didn't respect
the list* headers :(.

Thanks, Grant!

--
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
Oct 18 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: madsgormlarsen | last post by:
Hi I am making a html table builder, and would like every second row to be blue. So for that purpose I need a number that changes on every iteration of a while loop, for exampel so that a value...
1
by: Řyvind Isaksen | last post by:
Hello! I need to dynamic generate a SQL statement based on how many images a user select to upload. Here you see an example with 2 images. It can be up to 50 images and I dont want to write...
7
by: Matt B | last post by:
I have a need to alternate output row colour where not every row in the sequence is output, so I cannot base the colour on whether position() is odd or even. e.g. .... <xsl:for-each...
13
by: Patrick M. | last post by:
Hello. I just got the K&R 2nd Edition of "The C Programming Language". I also just finished exercise 1-13, and I've coded a much shorter, commented solution. I'm not sure if you're still updating...
0
by: David Helgason | last post by:
I think those best practices threads are a treat to follow (might even consider archiving some of them in a sort of best-practices faq), so here's one more. In coding an game asset server I want...
4
by: sconeek | last post by:
Hi all, I am generating a html based table with multiple rows of data coming in real time from a postgres DB. The underlying technology is java based however the front end is html. now i am...
1
by: lennyw | last post by:
Hi I'm trying to use XSLT to do an xml to xml transformation where the output xml contains summary data on the information in the input xml. I've succesfully done a Muenchian grouping of the...
6
by: ash | last post by:
i have a web page using frameset split into few pages. And I want to generate one page of HTML code and send it through email. My question is have to generate a HTML page using asp? Thx very much.
56
by: Zytan | last post by:
Obviously you can't just use a simple for loop, since you may skip over elements. You could modify the loop counter each time an element is deleted. But, the loop ending condition must be...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.