首页 > 解决方案 > python嵌套反向循环

问题描述

我正在尝试创建一个与 for 循环嵌套的反向循环,一旦 for 循环满足某个标准,然后反向循环就会启动,以获取我正在搜索的所需信息,基于第二个一致的标准,我知道。通常会执行 for 循环来查找所需的信息;但是,我只知道标准,除了在标准之前列出的信息之外,我不知道所需的信息,并且可以采用三种不同格式之一。我正在使用 Python 3.6。

编辑:看起来让我失望的是“我正在寻找的东西”的不同格式。为简化起见,只需使用 1 种特定格式,我想要的信息可以与我不想要的信息分组。

searchList = [['apple'], ['a criterion for'], 
['what Im looking for'], ['a criterion for what Im looking for   not what Im looking for'], 
['fish'], ['coffee'], ['oil']]
saveInformation = []
for n in range(len(searchList)):
    if 'coffee' in searchList[n]:
        for x in range(n, 0, -1):
            if 'a criterion for' in searchList[x]:
                 #this part just takes out the stuff I don't want
                 saveInformation.append(searchList[x])
                 break
            else: 
                 # the reason for x+1 here is that if the above if statement is not met, 
                 #then the information I am looking for is in the next row. 
                 #For example indices 1 and 2 would cause this statement to execute if index 
                 #3 was not there
                 saveInformation.append(searchList[x+1])
                 break

预期产出

saveInforation = ['what Im looking for']

相反,我得到的输出是

saveInforation = ['oil']

标签: pythonnested-loops

解决方案


我昨天回答了一个类似的问题,所以我会给你代码并解释你如何实现它。

首先你需要一个你已经拥有的列表,太棒了!让我们称之为wordlist。现在您需要一个代码来查找它

for numbers in range(len(wordlist)):
    if wordlist[numbers][0] == 'the string im looking for':
        print(wordlist[numbers])

推荐阅读