简体   繁体   中英

Exit nested for loop in python

I wanted to search through a csv file that will look up keywords from a list within the first two columns. I've managed to get it to work when a key word is found, but wanted to have a message if no keywords found. Unfortunately the message "not found" comes out four times. I just wanted this to come out once. Please can you help? What it's doing is going around each key word again.

import csv
keywords=["none","blank","off","screen","blank"]
f=open("CSVSolutions.csv")
for row in csv.reader(f):
    for keyword in keywords:
        if keyword == row[0] or keyword == row[1]:
            print(row[2])
            break
        else:
            print ("not found")
            break
f.close

Looks like you want to emit the message "Not found" only when the keywords were not found in the entire file?

try this:

import csv
keywords=["none","blank","off","screen","blank"]
f=open("CSVSolutions.csv")

for row in csv.reader(f):
    found = False;
    for keyword in keywords:
        if keyword == row[0] or keyword == row[1]:
            print(row[2])
            found = True
            break
    if not found:
        print ("not found")
        break

f.close()

The main point being that you should use another variable to track the state that you're looking for.

You can use for.. else here like so:

for keyword in keywords:
    if keyword == row[0] or keyword == row[1]:
        break
else:
    print("not found")
import csv
keywords=["none","blank","off","screen","blank"]

f=open("CSVSolutions.csv")
for row in csv.reader(f):
    if row[0] in keywords or row[1] in keywords:
        print(row[2])
    else:
        print ("not found")
f.close

I figured avoiding nested for entirely was easier. It may seem slower to iterate over the keywords list twice but it's basically equivalent to making two comparisons per item anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM