Python井字棋开发:迭代列表if判断异常与ValueError报错排查
问题根因与修复方案
报错原因
你触发ValueError: 'top-L' is not in list的核心问题是:winconditions.index(move)是在整个存储获胜组合的大列表中搜索move字符串,但winconditions的所有元素都是子列表,不存在直接的字符串元素,必然搜索失败抛出错误。
其他隐藏问题
- 列表索引用法错误:Python列表从0开始计数,每个获胜组合子列表的长度为3,合法索引是
0/1/2,你判断胜负时用each[1]/each[2]/each[3],不仅漏了第一个位置的判断,还会触发索引越界。 - 数据结构修改错误:你代码里直接执行
winconditions[update_wincon] = turn,会把整个获胜组合子列表直接替换成X/0字符串,后续遍历判断会完全失效。
修复后的代码
把循环判断胜负的部分替换为如下逻辑即可:
for each in winconditions: if move in each: # 找到当前子列表里move对应的位置,替换为当前玩家标识 idx = each.index(move) each[idx] = turn # 检查当前子列表是否所有元素都是当前玩家,判定胜负 if all(item == turn for item in each): print(f"{turn} is the winner!") exit() # 获胜后直接退出游戏
完整可运行的修正代码如下:
# board is stored as a dictionary theBoard = {'top-L': ' ', 'top-M': ' ', 'top-R': ' ', 'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ', 'bot-L': ' ', 'bot-M': ' ', 'bot-R': ' '} # function to convert dictionary into visual board def printBoard(board): print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R']) print('-+-+-') print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R']) print('-+-+-') print(board['bot-L'] + '|' + board['bot-M'] + '|' + board['bot-R']) # winconditions stored as list of winning combinations winconditions = [['top-L', 'top-M', 'top-R'], ['mid-L', 'mid-M', 'mid-R'], ['bot-L', 'bot-M', 'bot-R'], ['top-L', 'mid-L', 'bot-L'], ['top-M', 'mid-M', 'bot-M'], ['top-R', 'mid-R', 'bot-R'], ['top-L', 'mid-M', 'bot-R'], ['top-R', 'mid-M', 'bot-L']] turn = 'X' while True: printBoard(theBoard) print('Turn for ' + turn + '. Move on which space?') move = input() # input默认返回字符串,不需要额外转str if move not in theBoard: print('please enter top/mid/bot-L/M/R') continue theBoard[move] = turn # 修正后的胜负判断逻辑 for each in winconditions: if move in each: idx = each.index(move) each[idx] = turn if all(item == turn for item in each): print(f"{turn} is the winner!") exit() print(winconditions) # 切换玩家 turn = '0' if turn == 'X' else 'X'
内容的提问来源于stack exchange,提问作者br0steen
相关产品推荐
相关产品推荐

