简体   繁体   English

如果条件不满足,for循环退出

[英]for loop exit if condition is not met

I am trying to write a Shiritori game in Python.我正在尝试在 Python 中编写 Shiritori 游戏。 In the game you are given a word (ex: dog) and you must to add another word that starts with the end of the previous word ex(: doG, Goose).在游戏中给你一个单词(例如:dog),你必须添加另一个以前一个单词 ex(:doG,Goose)结尾的单词。 So given a list words = ['dog', 'goose', "elephant" 'tiger', 'rhino', 'orc', 'cat'] it must return all value, but if "elephant" is missing it must return: ["dog","goose"] because "dog" and "goose" match, but "goose" and "tiger" not.所以给定一个列表 words = ['dog', 'goose', "elephant" 'tiger', 'rhino', 'orc', 'cat'] 它必须返回所有值,但如果 "elephant" 缺失它必须返回: ["dog","goose"] 因为 "dog" 和 "goose" 匹配,但 "goose" 和 "tiger" 不匹配。

I am running into a bug where it either loop out of range checking next index in list or it returns only "dog" and not "goose", or it returns ["dog","goose"] and than exit the loop without iterating through the rest of the list(s).我遇到了一个错误,它要么循环超出范围检查列表中的下一个索引,要么只返回“dog”而不是“goose”,或者它返回 ["dog","goose"] 并且在不迭代的情况下退出循环通过列表的 rest。 What am I doing wrong?我究竟做错了什么?

def(game():
words = ['dog', 'goose', 'tiger', 'rhino', 'orc', 'cat']
check_words = ['goose', 'tiger', 'rhino', 'orc', 'cat']
# check words has one less element to avoid index out or range in the for loop
# example = if word[-1] != words[index+1][0]: # index+1 gives error
good_words = []
for index, word in enumerate(words):
    for index2, word2 in enumerate(check_words):
        # I want to add the correct pair and keep looping if True
        if word[-1] == word2[0]:
            good_words.extend([word,word2])
    return good_words # break out of the loop ONLY when this condition is not met
print(game())

your code need an indent after "def game():".您的代码需要在“def game():”之后缩进。

I am not sure why you needed the 2nd for loop.我不确定你为什么需要第二个 for 循环。

here is a solution.这是一个解决方案。

def game():
    words = ['dog', 'goose', 'elephant',  'utiger', 'rhino', 'orc', 'cat']
    good_words = []
    for index in range(0, len(words)):
        if index+1 < len(words):
            previous_word = words[index][-1]
            next_word = words[index+1][0]
            if previous_word == next_word:
                # appends the new word if not in list
                if words[index] in good_words:
                    good_words.append(words[index+1])
                else:
                    # only used for the first time to append the current and the next word
                    good_words.append(words[index])
                    good_words.append(words[index+1])
        else:
            return good_words # break out of the loop ONLY when this condition is not met
    return good_words
print(game())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM