嵌套循环在扫描列表时意外中断

时间:2018-08-20 12:58:06

标签: python

我对Python 2.7还是很陌生的(不定期地仅编码4-5个月),我认为我对嵌套循环的工作方式有误解。

目标是检查文件的字符串,并通过readlines()加载到列表中,并提取某些信息块。

如上所述加载.txt文件后,我将从以下内容开始:

for index, line in enumerate(conf_remoto):
    if 'string1' in line or 'string2' in line:
        temp_int_list = []  # initialize list
        temp_int_list[:] = [] # clean list
        temp_int_list.append(line) # append the entire line matching
        tempindex = index+1 # temporary counter, to start examining next element
        scanned_list = block_scan(tempindex, conf_remoto) # call the scanning function and pass the relevant data

def block_scan(tempindex, conf_remoto):
    temp_list = []
    temp_list[:] = []
    for i in range(tempindex, len(conf_remoto)): #loop to examine next lines
        print "Examining" + conf_remoto[i] #Cosmetic to show where I am in the loop
        print "Counter = " + str(i)
        if 'string3' in str(conf_remoto[i]) or 'string4' in str(conf_remoto[i]) or 'backup peer' in str(conf_remoto[i]):
            temp_list.append(str(conf_remoto[i])) # if any of these is found, append the entire element/string
        if 'stringbreak' in str(conf_remoto[i]): #stop the loop once you find that
            return temp_list

换句话说:

  1. 我首先将.txt文件加载到列表中,以便列表的每个元素都包含一行txt(通过readlines()

  2. “ for index,enumerate(name_list)中的行”开始扫描整个列表,以查找每个元素中的两个字符串(string1或string2)

  3. 找到一个字符串之一后,我调用block_scan()并将其传递给整个列表以及列表中与字符串1/2匹配的位置+1,从而使{{1 }}从列表中的下一个位置/行开始

  4. block_scan()从匹配string1 / 2的位置/行开始block_scan()循环,直到列表末尾。

  5. 如果for在元素block_scan()中找到任何所需的字符串3/4/5,它将整行追加到一个临时列表中,该列表仅在以下情况下返回给调用者:在列表中找到某个“停止”字符串,有效地结束了循环。

简而言之,我的目标是使用循环扫描文件以查找某个字符串1/2的所有出现,然后扫描该出现与字符串1/2的下一个首次出现之间的所有行,并确定两次出现的string1 / 2之间的行块之外的行。

当前代码似乎不起作用,因为print语句向我显示list[i]中的循环仅扫描列表中的下一个元素/行,而不扫描所有行,直到下次出现string1 / 2。

我不明白为什么block_scan()内的循环应该在第一行停止,因为它是另一个函数中包含的循环。我不明白为什么(如果是这种情况)主循环会影响其行为。

1 个答案:

答案 0 :(得分:0)

恕我直言,您的代码很弱,无法正常工作,但是您提供的缩进太乱了,以致无法弄清您要搜索的内容。

执行此循环:

for i in range(tempindex, len(conf_remoto)): 
    if 'string3' in str(conf_remoto[i]) or 'string4' in str(conf_remoto[i]) or 'backup peer' in str(conf_remoto[i]):
        temp_list.append(str(conf_remoto[i])) 
        if 'stringbreak' in str(conf_remoto[i]): 
             return temp_list

这不同于:

for i in range(tempindex, len(conf_remoto)): 
    if 'string3' in str(conf_remoto[i]) or 'string4' in str(conf_remoto[i]) or 'backup peer' in str(conf_remoto[i]):
        temp_list.append(str(conf_remoto[i])) 
    if 'stringbreak' in str(conf_remoto[i]): 
        return temp_list

在两种情况下,如果未找到预期的序列{'string3'...'stringbreak'},默认返回值是多少?

编辑: 感谢您纠正缩进。让我们尝试建立一个常见的例子

#Dummy configuration file
Introduction

Il y a un an à peu près, qu’en faisant à la Bibliothèque royale des 
recherches pour mon histoire de Louis XIV, je tombai par hasard sur les 
Mémoires de M. d’Artagnan, imprimés – comme la plus grande partie des 
ouvrages de cette époque, où string1 les auteurs tenaient à dire la
vérité sans aller faire un tour plus ou moins long à la Bastille – à 
Amsterdam, chez Pierre Rouge. Le titre me séduisit : je les emportai chez 
moi, avec la permission de M. le conservateur ; bien entendu, je les dévorai.

string3 Mon intention n’est pas de faire ici une analyse de ce curieux 
ouvrage, et je me contenterai d’y renvoyer ceux de mes lecteurs qui 
apprécient les tableaux d’époques. Ils y trouveront des portraits crayonnés 
de main de maître ; et, quoique les esquisses soient, pour la plupart du 
temps, tracées stringbreak sur des portes de caserne et sur des murs de 
cabaret, ils n’y reconnaîtront pas moins, aussi ressemblantes que dans 
l’histoire de M. Anquetil, les images de Louis XIII, d’Anne d’Autriche, 
de Richelieu, de Mazarin et de la plupart des courtisans de l’époque.

您发布的程序收益:

['string3 Mon intention n\xe2\x80\x99est pas de faire ici une analyse de ce curieux \n']

(我使用的是法语语言环境和法语文本,因此重音字符的显示方式可能会发生变化,这无关紧要)

您能否在此示例中指定期望作为“正确输出”的内容?

编辑2

此答案不仅试图回答您的问题,而且还试图 教您如何构建一个重要的测试用例,该用例非常简单,可以被所有人共享。在您的私人消息中,您指定了不同情况下的预期输出,而上一示例未涵盖。因此,现在就将其包括在内(我清除了法语语言环境字符)。复制并粘贴此文本,然后将其另存为文本文件。

#Dummy configuration file
Introduction

Il y a un an a peu pres, qu'en faisant a la Bibliotheque royale des 
recherches pour mon histoire de Louis XIV, je tombai par hasard sur les 
Mémoires de M. d'Artagnan, imprimés – comme la plus grande partie des 
ouvrages de cette époque, ou string1 les auteurs tenaient a dire la
verite sans aller faire un tour plus ou moins long a la Bastille – a 
Amsterdam, chez Pierre Rouge. Le titre me seduisit : je les emportai chez 
moi, avec la permission de M. le conservateur ; bien entendu, je les 
devorai.

string3 Mon intention n'est pas de faire ici une analyse de ce curieux 
ouvrage, et je me contenterai d'y renvoyer ceux de mes lecteurs qui 
apprecient les tableaux d'epoques. Ils y trouveront des portraits crayonnes 
de main de maitre ; et, quoique les string4 esquisses soient, pour la 
plupart du temps, tracees stringbreak sur des portes de caserne et sur des 
murs de cabaret, ils n'y reconnaîtront pas moins, aussi ressemblantes que 
dans l'histoire de M. Anquetil, string4 les images de Louis XIII, d'Anne 
d'Autriche, de Richelieu, de Mazarin et de la plupart des courtisans de 
l'epoque.

我的代码是:

with open('testme_nested.txt', 'r') as textfile:
    conf_remoto = textfile.readlines()

for index, line in enumerate(conf_remoto):
    #print line
    if 'string1' in line or 'string2' in line:
        print '>>>>*'
        temp_int_list = []  # initialize list
        temp_int_list.append(line) # append the entire line matching
        tempindex = index+1 # temporary counter, to start examining next element
        scanned_list = block_scan(tempindex, conf_remoto) # call the scanning function and pass the relevant data
        print 'Actually I found this block:'
        print scanned_list

def block_scan(tempindex, conf_remoto):
    temp_list = []
    for i in range(tempindex, len(conf_remoto)): #loop to examine next lines
        print "Examining" + conf_remoto[i] #Cosmetic to show where I am in the loop
        print "Counter = " + str(i)
        if 'string3' in str(conf_remoto[i]) or 'string4' in str(conf_remoto[i]) or 'backup peer' in str(conf_remoto[i]):
            temp_list.append(str(conf_remoto[i])) # if any of these is found, append the entire element/string
        if 'stringbreak' in str(conf_remoto[i]): #stop the loop once you find that
            return temp_list

在此文件上运行代码时,我得到:

  

实际上我找到了这个块:   [“ string 3 Mon意图意图公平分析”,主权利; et,quoique les string4 squisses soient,pour la \ n']

您能告诉我这种行为怎么了吗?