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

Python 扫描列表时嵌套循环意外中断,python,Python,我对Python2.7相当陌生(不定期地编写了4-5个月的代码),我想我对嵌套循环的工作原理有一个误解 目标是检查通过readlines()加载到列表中的文件字符串,并提取某些信息块 如上所述加载.txt文件后,我从以下内容开始: for index, line in enumerate(conf_remoto): if 'string1' in line or 'string2' in line: temp_int_list = [] # initialize lis

我对Python2.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
换言之:

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

  • “for index,line in enumerate(name_list)”开始扫描整个列表,在每个元素中查找两个字符串(string1或string2)

  • 当找到其中一个字符串时,我调用
    block\u scan()
    并将整个列表和列表中字符串1/2匹配的位置+1传递给它,以便使
    block\u scan()
    从列表中的下一个位置/行开始

  • block_scan()

  • 如果
    block\u scan()
    在元素
    list[i]
    中找到任何所需的字符串3/4/5,它会将整行追加到一个临时列表中,只有在列表中找到某个“stop”字符串时才会返回给调用方,从而有效地结束循环

  • 简单地说,我的目标是用循环扫描一个文件,以找到某个string1/2的所有引用,扫描所述引用和string1/2的下一个第一个引用之间的所有行,并从string1/2的两个引用之间包含的行块中找出某些行

    当前代码似乎不起作用,因为print语句显示
    block_scan()
    中的循环只扫描列表中的下一个元素/行,而不是所有行,直到下一次出现string1/2


    我不明白为什么
    block\u scan()
    中的循环应该在第一行停止,因为它是包含在不同函数中的循环。我不明白为什么(如果是这样的话)主循环会影响它的行为。

    IMHO,您的代码很弱,无法工作,但是您提供的缩进非常混乱,以至于无法了解您正在搜索的内容

    以这个循环为例:

    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
    
    当我在此文件上运行代码时,我得到:

    实际上我找到了这个街区: [“我的意图是不公平的,我不需要对古董进行分析”,“我的主要作品,我的作品,我的作品”]


    你能告诉我这种行为有什么问题吗?

    你好。请检查你的缩进。另外,您能提供一些示例数据吗?例如,如果conf_remoto为['foo','bar',,则预期输出为。。。真正的输出是…在读取文件时,您使用了:conf_remoto=file.readlines()?初始化后立即“清理”临时int_列表有什么意义?你需要它做什么,因为你似乎从来没有使用过它?谢谢,我想现在缩进应该更好了@Sharku yes我将open(filepath,'r')用作myfile,conf\u remoto=myfile.readlines()。在Lorenzo,它是一个配置文件,所以您可能会有这样的行:1)接口x/y 2)描述blah 3)接口x/z@tobias_k实际上,这是我用来确保每次调用函数时都清理临时列表的技巧,因为我不太确定在函数结束后列表的内容是否会被处理掉。它可能是多余的,但在我对列表/对象的行为有了更多的了解之前,它比抱歉更安全。代码正确地找到了“stringbreak”,因此它处理整个conf_remoto列表,但在找到时,输出不会显示任何string3/4或附加到临时列表的任何其他字符串。这表明代码没有处理这些行(我绝对肯定这些string3和string4显然在列表中),谢谢Lorenzo。假设在一行中找到string3,循环应将找到string3的整行追加到临时_列表中,临时_列表的元素将依次追加到主循环末尾的另一个主_列表中。例如,我们假设您正在按段落进行此操作……您希望主循环找到第1段的开头,开始一个二次循环,它将检查第1段开头之间的所有行,直到找到第2段的开头,这将结束二次循环。最后,它是一个配置解析器,用于提取relevnt linesthank以编辑缩进。一般来说,应该避免使用索引,最好使用迭代器。但我仍然需要了解你的期望…谢谢你的评论。请您提供给定示例的预期答案,或者编辑我的答案?不是口头描述,而是预期列表或列表列表。