The Python Oracle

how to break out of only one nested loop

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 How To Break Out Of Only One Nested Loop
01:29 Accepted Answer Score 41
01:58 Answer 2 Score 4
02:16 Thank you

--

Full question
https://stackoverflow.com/questions/1855...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #loops #nested #break

#avk47



ACCEPTED ANSWER

Score 41


break and continue apply to the innermost loop.

The issue is that you open the second file only once, and therefore it's only read once. When you execute for y in file2.readlines(): for the second time, file2.readlines() returns an empty iterable.

Either move file2 = open(filename2, 'r') into the outer loop, or use seek() to rewind to the beginning of file2.




ANSWER 2

Score 4


You need to parse the numeric strings to their corresponding integer values.

You can use int('hoge') as follows.

import sys

filename1 = sys.argv[1]
filename2 = sys.argv[2]

with open(filename1) as file1:
    for x in file1:
        with open(filename2) as file2:
            col = x.strip().split()
            for y in file2:
                col2 = y.strip().split()
                if col[1] == col2[1] and int(col[3]) < int(col2[2]):
                    print x