How to iterate over a string using a buffer (python)

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

I currently have

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

But consecutive for loops will reset the iteration at the beginning.

Is there anything in python for this, or do I need to write it from scratch?

+3
source share
4 answers

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
+2
source

Just use the generator expression (genexp) instead of the list (listcomp) that you are using now - ie:

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

- ( os.linesep, - Python \n...), , do - ( ) (), .

, , for line in sList:, , ( - break), - , ?

+13

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
0
source

Hack an iterator?

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

Then just call iterOverList () in the loop several times, will it save the state?

0
source

Source: https://habr.com/ru/post/1726197/


All Articles