python嵌套反向循环

2024-10-04 11:33:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个嵌套了for循环的反向循环,一旦for循环满足某个条件,那么反向循环就会启动,以获取我所搜索的所需信息,基于我所知道的第二个、一致的条件。通常会执行for循环来查找所需的信息;但是,我只知道准则,不知道所需的信息,只知道准则之前列出的信息,可以是三种不同格式中的一种。我使用的是python3.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']

Tags: thein信息forifis格式not
3条回答

我认为最好不要嵌套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)

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

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 in itemsWanted替换if item == 'im looking for'

作为补充说明,您可以通过在开始时执行if语句来减少执行的检查数:

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

相关问题 更多 >