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

Python实现Hangman游戏时字符串遍历索引使用错误问题

Hangman游戏字符匹配遍历报错修复

开发Hangman(绞刑架猜词)游戏时,核心逻辑为比对玩家输入的字母playerLetter与目标关键词的所有字符,初始实现代码如下:

for i in currentWord:
      if playerLetter == letterList[i]:
          print('Yes, there is a ' + str(playerLetter) + ' in the word')
          answerList[i] = playerLetter
          win +=1
          yes = 1

涉及变量说明:

  • currentWord:目标猜词,字符串类型,示例值为"people"
  • letterList:对currentWord做list()转换得到的字符列表
  • answerList:存储已猜对字符的展示列表,用于实时更新猜词进度
  • win:猜对字符计数变量,累计值等于单词长度时判定玩家通关
  • yes:单轮猜中标记位,用于区分本轮猜中/猜错的分支逻辑

错误原因

Python中直接用for i in <字符串>做遍历,循环变量i的取值是字符串内的单个字符,而非数字索引。拿字符值作为下标访问列表,会触发类型错误,无法定位到列表的对应位置。

修复方案

将遍历逻辑改为按索引范围遍历即可解决问题,修改后代码可正常运行:

for i in range(len(currentWord)):
      if playerLetter == letterList[i]:
          print('Yes, there is a ' + str(playerLetter) + ' in the word')
          answerList[i] = playerLetter
          win +=1
          yes = 1

可选优化写法

更符合Python编码习惯的实现可以用enumerate()同时获取索引和对应字符,不需要提前将字符串转为字符列表,可读性更高,也能避免索引类型用错的问题:

for idx, char in enumerate(currentWord):
    if playerLetter == char:
        print(f'Yes, there is a {playerLetter} in the word')
        answerList[idx] = playerLetter
        win += 1
        yes = 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 17:31:05