Search code examples
pythonnested-loops

python nested reverse loop


I'm trying to create a reverse loop nested with a for loop, once the for loop meets a certain criterion then the reverse loop kicks in to obtain the required information I'm searching for based off of a second, consistent, criterion that I know. Normally one would do the for loop to look for the required information; however, I only know the criterions and I don't know the required information other than it's listed prior to the criterions and can be in one of three different formats. I'm using Python 3.6.

EDIT: It looks like what's throwing me off is the different formatting of 'what I'm looking for'. To simplify it lets just go with 1 specific format, the information I want can be grouped with information I don't want.

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

Expected output

saveInforation = ['what Im looking for']

Instead the output I'm getting is

saveInforation = ['oil']

Solution

  • I think it's better not to nest the for loops, but instead split up the problem in distinct steps. It's probably even best to make a separate function for each step.

    Your requirements are not entirely clear to me, but I think this does what you need:

    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)