Taking control of a for loop (python)

I have a program that contains a for loop inside another for a loop that creates a string, and I have an if statement that checks the key in the string.

here is an example

list1=[var1,var2,var3] list2 = [file1,file2,file3] for v in list1: //do stuff that returns a string, string.splitlines() for f in list2: for line in string if key in line and f in line: print "line" break else: continue 

I get the result that I am looking for, but I want to control the loop, I mean, in the first iteration, we have var1 and it will go through files file1, file2 and file3, and then the next iteration var2, and this will go through through file1, file2, file3 and so on and so forth.

How can I change it so that when it finds a string, it will not go any further since var1 instead accepts var2 and then continue? I tried to follow

 i = iter(list1) j = iter(list2) 

and after the print line

 if key in line and f in line: print "line" i.next() j.next() break 

But that doesn't seem to do anything, any tips on how to achieve this?

+4
source share
4 answers

I recommend putting the inner two loops in the corresponding function. When you find the key, return from the function.

 list1=[var1,var2,var3] list2 = [file1,file2,file3] for v in list1: //do stuff that returns a string, string.splitlines() find_line(string) 

and then:

 def find_line(string): for f in list2: for line in string if key in line and f in line: print "line" return else: continue 
+5
source

You can use the variable to control the splitting of nested loops:

 for v in list1: //do stuff that returns a string, string.splitlines() done = False for f in list2: if done = True: break for line in string if key in line and f in line: print "line" done = True break else: continue 
+1
source

You can set a flag to indicate when you found it.

 for v in list1: //do stuff that returns a string, string.splitlines() flag = False for f in list2: for line in string: if key in line and f in line: print "line" flag = True break if flag: break 
0
source

Smallest solution would be logical

a

 for v in list1: # do your code here foundCurrentVar = False for f in list2: if foundCurrentVar: break for line in string if key in line and f in line: print "line" foundCurrentVar = True break else: continue 
0
source

All Articles