Python Hangman游戏重复字母匹配问题修复求助
Hangman游戏重复字母匹配问题解决
问题描述
我正在用Python开发Hangman(猜词游戏),使用以下代码判断输入字母是否在目标词中,并更新display列表展示已猜出的字母:
if guess in word: if guess not in display: for a in word_sliced: print(a) if a == guess: location = word_sliced.index(a) display[location] = guess else: continue else: print("guess already used!") else: print("Oh no! Its not in the word!") health -= 1
当前问题是仅能匹配到一个重复字母,例如目标词为book,用户猜o时,display仅变为['_', 'o', '_', '_'],而非预期的['_', 'o', 'o', '_']。
问题原因
word_sliced.index(a)方法只会返回第一个匹配字符的索引,所以遇到重复字母时,只会更新第一个对应位置,后续重复字母的位置不会被修改。
修改后的代码
if guess in word: if guess not in display: # 同时遍历索引和字符,定位所有匹配位置 for idx, char in enumerate(word_sliced): if char == guess: display[idx] = guess else: print("guess already used!") else: print("Oh no! Its not in the word!") health -= 1
说明
- 使用
enumerate()函数可以在遍历word_sliced时,同时获取每个字符的索引idx和字符值char,这样就能精准找到所有等于guess的位置并更新display。 - 保留了原有的“已使用字母”判断逻辑,避免重复处理同一个字母。
内容的提问来源于stack exchange,提问作者Risen_Storm
相关产品推荐
相关产品推荐

