You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Hangman游戏开发:如何将猜中字母插入display列表对应位置

Hangman游戏:猜中字母后更新display列表的解决方案

你的代码已经完成了display列表的初始化,但缺少猜中字母时替换对应下划线的核心逻辑。要实现这个功能,你需要遍历目标单词的每个字符,匹配玩家猜中的字母后,更新display列表对应位置的内容。

修改后的完整代码

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)

guess = input("Guess a letter: ").lower()

display = []
chosen_word_length = len(chosen_word)
for _ in range(chosen_word_length):
    display.append("_")

# 核心逻辑:遍历目标单词,替换猜中的字母
for index, char in enumerate(chosen_word):
    if char == guess:
        display[index] = char

print(display)

关键逻辑说明

  • 使用enumerate(chosen_word)可以同时获取每个字符的索引和字符本身,这是定位display列表位置的关键
  • 对比当前字符与玩家输入的guess,如果匹配,直接修改display列表对应索引位置的元素(从下划线改为该字母)
  • 比如当chosen_word是"aardvark",玩家猜"a"时,display会输出['a', 'a', '_', '_', 'a', '_', '_', 'k']

内容的提问来源于stack exchange,提问作者snowhow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 18:30:43