I am probably going about this in the wrong manner, but I was wondering how to handle this in python.
First some c code:
int i;
for(i=0;i<100;i++){
if(i == 50)
i = i + 10;
printf("%i\n", i);
}
Ok so we never see the 50’s…
My question is, how can I do something similar in python? For instance:
for line in cdata.split('\n'):
if exp.match(line):
#increment the position of the iterator by 5?
pass
print line
With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true.
There has got to be a better way to do this, hopefully one that does not involve importing another module.
Thanks in advance!
There is a fantastic package in Python called
itertools.But before I get into that, it’d serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the
__iter__()class method that provides an iterator type. “Understanding Python’s ‘for’ statement” is a nice article covering how thefor-instatement actually works in Python and provides a nice overview on how the iterator types work.Take a look at the following:
Now back to
itertools. The package contains functions for various iteration purposes. If you ever need to do special sequencing, this is the first place to look into.At the bottom you can find the Recipes section that contain recipes for creating an extended toolset using the existing itertools as building blocks.
And there’s an interesting function that does exactly what you need:
Here’s a quick, readable, example on how it works (Python 2.5):