How to iterate over a string using a buffer (python)
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 hav开发者_Go百科e to write one from scratch?
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?
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
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
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?
精彩评论