【问题标题】:for loop exit if condition is not met如果条件不满足,for循环退出
【发布时间】:2021-08-22 11:14:44
【问题描述】:

我正在尝试用 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())

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      我不确定你为什么需要第二个 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())
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-12
        • 2022-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多