views:

357

answers:

4

Hi all,

I'm trying to find some code that, given a string, will allow me to iterate over each line using the for loop construct, but with the added requirement that separate for loop constructs will not reset the iteration back to the beginning.

At the moment I have

sList = [line for line in theString.split(os.linesep)]
for line in SList
  ... do stuff

But successive for loops will reset the iteration back to the beginning.

Does something in python exist for this, or will I have to write one from scratch?

Thanks

Tarsa

A: 

Try using a combination of slices and enumerate():

sList = theString.split(os.linesep)
for i, line in enumerate(sList):
    if foo: 
        break

for j, line in enumerate(sList[i:]):
    # do more stuff
J.J.
+10  A: 

Just use a generator expression (genexp) instead of the list comprehension (listcomp) you're now using - i.e.:

sList = (line for line in theString.split(os.linesep))

that's all -- if you're otherwise happy with your code (splitting by os.linesep, even though normal text I/O in Python will already have translated those into \n...), all you need to do is to use parentheses (the round kind) instead of brackets (the square kind), and you'll get a generator instead of a list.

Now, each time you do a for line in sList:, it will start again from where the previous one had stopped (presumably because of a break) -- that's what you're asking for, right?

Alex Martelli
Ah, well done, sir. Thanks for teaching me something about the newer python features.
J.J.
What version of python was genexp introduced? We're using 2.2 at the moment, and I get a syntax error using your suggestion
Taras
@Taras, they came in with 2.4, a bit more than 5 years ago. An explicit call to `iter`, as in Federico's answer that you suggested, works in 2.2. (If you need help about a version that's 5 releases and 5 years behind, indicating it in your questions will be far more useful than belatedly mentioning it in comments;-).
Alex Martelli
Point taken - will put the version information into my next question :*)
Taras
A: 

Hack at an iterator?

def iterOverList(someList):
    for i in someList:
        # Do some stuff
        yield

Then just call iterOverList() within a loop a few times, it'll retain state?

Richo
`s/yeild/yield/`
ndim
Oops brainfart. /thanks
Richo
Was hoping there was a simpler way! Looks like there is, see @Federico below
Taras
+2  A: 

Use another iterator:

aList = range(10)
anIterator = iter(aList)

for item in anIterator:
    print item
    if item > 4: break

for item in anIterator:
    print item
Federico Ramponi