python 嵌套反向循环

python nested reverse loop

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

编辑:看起来让我失望的是“我正在寻找的内容”的不同格式。为了简化它,我们只使用一种特定格式,我想要的信息可以与我不想要的信息分组。

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']

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

First you need a list which you already have, great! Let's call it wordlist. Now you need a code to look for it

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

你可以使用一个小的列表理解来达到类似的效果:

search = ['apple', 'im looking for', 'coffee', 'fish']
results = [item for item in search
           if 'coffee' in search
           and item == 'im looking for']

这将执行您需要的检查,仅将您想要的项目添加到新列表中,即使如此,也只有在您的标准项目存在时才如此。

您甚至可以像这样添加更多要搜索的项目:'

itemsWanted = ['im looking for', 'fish']

然后在您的列表理解中将 if item == 'im looking for' 替换为 if item in itemsWanted

附带说明一下,您可以通过在开头执行 if 语句来减少执行的检查次数:

if 'coffee' in search: # criterion matched
    results = [i for i in search
               if i in itemsWanted]

我认为最好不要嵌套 for 循环,而是将问题分成不同的步骤。最好为每个步骤创建一个单独的函数。

我不太清楚您的要求,但我认为这可以满足您的需求:

def search_forward(searchList, key):
    for i, element in enumerate(searchList):
        if key in element:
            return i
    raise ValueError

def search_backward(searchList, key, start):
    for i in range(start - 1, -1, -1):
        if key in searchList[i]:
            return i
    raise ValueError

searchList = [['apple'], ['a criterion for'], 
['what Im looking for'], ['a criterion for what Im looking for   not what Im looking for'], 
['fish'], ['coffee'], ['oil']]

coffee_index = search_forward(searchList, 'coffee')
a_criterion_for_index = search_backward(searchList, 'a criterion for', coffee_index - 1)
saveInformation = searchList[a_criterion_for_index + 1]
print(saveInformation)