I find code like this in a lot of web applications:
list_of_x_objects = ['a', 'b', 'c', 'd', 'e']
for i, x in enumerate(list_of_x_objects):
if i % 2: htmlclass = "odd"
else: htmlclass = "even"
print """
""" % (htmlclass, x)
Never mind the print statement. That’s just to illustrate the point without having to explain some template syntax.
The same thing can be expressed with itertools.cycle:
list_of_x_objects = ['a', 'b', 'c', 'd', 'e']
for htmlclass, x in zip(itertools.cycle(['odd', 'even']), list_of_x_objects):
print """
""" % (htmlclass, x)
I see several advantages of the second approach:
- It’s way more flexible. I can easily switch to a style that repeats every three lines (or four, or five…).
- I don’t create the variable i when all I really want is a class variable that toggles between values.
- The second approach avoids the modulus operator. Since I hardly ever use the modulus operator, when I do come across it, I always have to take a second and puzzle out what’s happening.
nice. Modulus is typically a slow operation, as well. Not that I’ve benchmarked any of this … quite likely that some kind soul has optimized it in python.
Modulus operator is not so bad 🙂 You could use also:
list_of_x_objects = ['a', 'b', 'c', 'd', 'e']
for i, x in enumerate(list_of_x_objects):
print """%s""" % ( ("odd","even")[i%2], x)
This posting is marvelous and what a fantastic research that you have done. It has helped me a lot. thank you very much.
It's realy nice i posted ur story on my blog
respect
jimmy banger
______________________________________________
pass a drug test | how to beat a drug test | beat a drug test
I digged this for more news from you.
Thanks
Reena Verma
______________________________________________