-1

Is it possible to skip lines in a for statement? i.e....

for line in xrange(len(lines)):
    if line is True and line+1 is True and line+2 is True
        do something....

I'd like to skip ahead to line+3 in the next for loop after this one, because I have already looked at line+1 and line+2.

I have looked at continue and break as solutions but they do not seem to really solve the issue.

EDIT - To add on some clarification.... The data (text files) I am looking at don't simply come in sets of 3....I am going through football game logs...to give an example of code: Denver kicks off to Kansas City Kansas City returns the ball to the 20 yard line Kansas City offense, Q1 and 15:00 left to go Kansas City uses shotgun and gains 6 yards Denver called a dime defense

The last 3 lines would basically be a play and would give me all the pertinent info I need (Offense, Defense, plays called, yards gained, etc)... But the first two lines are a kickoff and I do not want to process those lines..

Hopefully this will provide clarity.

bondra76
  • 99
  • 7
  • It would help if you gave a clearer picture of the overall purpose of the code. What are the `lines`? What kind of pattern are you trying to detect? Supposing that the condition in the `if` statement *isn't* met; should you then try an "overlapping" position? Or you you actually want to *always* consider the source data in discrete sets of 3 lines? Because in that case there's a very neat duplicate I could refer you to. – Karl Knechtel Jul 23 '20 at 03:10
  • seems duplicate with this https://stackoverflow.com/a/2990152/4026902 – RY_ Zheng Jul 23 '20 at 03:10

4 Answers4

0

You could increment line by 3 every time:

for line in xrange(len(lines), 3):

Also, it seems that you are using Python 2 because of the xrange. Unless you have a specific reason for doing so, I would suggest that you use Python 3 because Python 2 has been deprecated.

In Python 3, you would write this as:

for line in range(len(lines), 3):
izhang05
  • 744
  • 2
  • 11
  • 26
0

Pretty sure this isn't going to be the most optimal solution but

for i in xrange(0,len(lines)-2,3):
    if lines(i) and lines(i+1) and lines(i+2):
        do something...

xrange will act in steps of 3, skipping to line3.

ZWang
  • 832
  • 5
  • 14
0

You can use either

for line in xrange(2, len(lines)):
    # do something

or

for line in xrange(len(lines)):
    if line < 2:
        continue
    # else, do something
Noah May
  • 1,049
  • 8
  • 18
0

A pythonic solution without indexes

import itertools as it

lst = [True, True, True, False, True, True, True, True, True]
glen = 3
grouped = zip(*[iter(lst)]*glen)
for g, i in zip(grouped, it.count()):
    if all(g):
        print(g, i)

Produces

(True, True, True) 0
(True, True, True) 2

It assumes the checking on boolean True is generic, i.e. it can be zero, an empty list, etc. If it needs to be specific to the value True we must change the call to all

Pynchia
  • 10,996
  • 5
  • 34
  • 43