简体   繁体   English

在python中退出嵌套循环

[英]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. 我想搜索一个csv文件,该文件将从前两列的列表中查找关键字。 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.. else 在这里像这样:

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. 遍历关键字列表两次似乎较慢,但是从本质上讲,它等效于对每个项目进行两次比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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