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

Hangman游戏中list.remove在元素相同时删错项问题求助

问题原因

你的代码核心问题出在wordFinder.remove(wordFinder[i])这一行:

  • list.remove(x)方法的逻辑是查找列表中第一个等于x的元素并删除,而非删除指定索引位置的元素。
  • 当wordFinder里存在多个相同的下划线(_)时,比如当前状态是["_", "e", "_", "_"],要处理索引2的位置,wordFinder[i]是_,remove会直接删掉第一个_(索引0的元素),后续插入操作的位置自然就错了,导致字母左移。
  • 换成其他字符(如(、.)没问题,是因为这些字符在列表里唯一,remove能精准找到对应位置的元素。
修复方案

完全不需要用remove和insert,直接通过索引赋值替换指定位置的元素即可,这是列表操作最直接高效的方式:

修改后的代码片段:

for i in range(len(word)):
    if guess == word[i]:
        print(i)
        found += 1
        # 直接替换指定索引的元素,无需删除插入
        wordFinder[i] = guess
    else:
        print("Wrong guess!")
额外优化建议

可以提前判断当前位置是否已经被猜对(比如不是下划线),避免重复计数:

for i in range(len(word)):
    if guess == word[i]:
        if wordFinder[i] != "_":
            continue  # 已经猜对过这个位置,跳过
        print(i)
        found += 1
        wordFinder[i] = guess
    else:
        print("Wrong guess!")

这样可以防止用户重复猜同一个正确字母时,found计数器错误累加。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:55:22