【发布时间】: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