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

时间:2021-06-04 11:37:48

标签: python for-loop if-statement indexing enumerate

我正在尝试用 Python 编写 Shiritori 游戏。在游戏中你得到一个单词(例如:dog),你必须添加另一个以前一个单词 ex(: doG, Goose) 结尾开头的单词。 所以给定一个列表 words = ['dog', 'goose', "elephant" 'tiger', 'rhino', 'orc', 'cat'] 它必须返回所有值,但如果缺少“elephant”,它必须返回: ["dog","goose"] 因为"dog"和"goose"匹配,但"goose"和"tiger"不匹配。

我遇到了一个错误,它要么循环超出范围检查列表中的下一个索引,要么只返回“dog”而不返回“goose”,或者返回 ["dog","goose"] 然后退出循环而不遍历列表的其余部分。 我做错了什么?

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())

2 个答案:

答案 0 :(得分:0)

您的代码需要在“def game():”之后缩进。

答案 1 :(得分:0)

我不知道你为什么需要第二个 for 循环。

这是一个解决方案。

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())