开发者

Most straightforward alternative to a while loop in python

The general point of the program is to search for words and make sure that they occur in the right order.

I am currently using the code

while not corpus[index_F2-1] == corpus[index_B]:
    index_F2 = corpus.index(corpus[index_F2], index_F2+1) 

in order to search for a word, check to make sure that a given word appears before it, and find a different instance of the same word in the corpu开发者_开发知识库s if the word does not appear in the correct environment. The only problem with this code is that, if the conditions are never met, it returns an error. Rather than having it return an error, it would be better if it could exit the loop, and then assign a new value to "F2" in order to try again. The obvious way to make the program exit the loop would be to use a while loop, but I am unsure how to get a while loop to not find a new value for F2 if the current one works. In short, it would work best if the script ran in this order.

  1. Check to see if the current F2 will ever work
  2. If it will not work, assign a new value to F2.
  3. Check again recurse and check to see if the new F2 will work
  4. and so on

An if statement would probably be in order, but exactly where and how it would work, I am unsure. Also, the code for reassigning F2 already exists. It is

index_E2= corpus.index(corpus[index_E2], index_E2+1)

index_F = index_E2+1

index_F2 = corpus.index(corpus[index_F], index_F+1)

A future problem that could present itself is that the corpus may run out of F2 values ( as a result of running out of E2 values) and display a similar error, but that is another issue.


I think I might understand what you're looking for. It sounds like you want to have multiple nested loops, with an exit point within the innermost loop. The most obvious way to achieve this, in my mind, is to enclose the loops within a function. Since all this corpus stuff is confusing, I'll use a simple example:

words_to_find = ['tree', 'cow', 'lots_of_other_words']
words_to_search = ['bathtub', 'more_words']
def find_words(words_to_search, words_to_find):
    for i, fword in enumerate(words_to_find):
        for j, sword in enumerate(words_to_search):
            if fword == sword: 
                return (fword, i, j)

You can nest as many loops as you like here -- for, while, whatever -- and still break out of all of them easily once you've found what you want.

Let me know if that doesn't answer your question.


EDIT: I suppose if you wanted to have it all in one while loop you could do this:

word_list = ['blah', 'blah2', 'etc']
word_list2 = ['other', 'words']
i = 0
j = 0
while True:
    if i == len(word_list):
        i = 0
        j += 1
    elif thing_I_want(word_list[i], word_list2[j]):
        do_something()
        break
    else:
        i += 1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜