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

使用Python类时出现意外列表赋值问题排查

井字棋Board类列表赋值异常问题

我在实现井字棋的Board类时遇到了意外的列表赋值问题,代码如下:

class Board():
    """Board class for Tic Tac Toe game. Board can be 3x3, 4x4, or 5x5."""
    def __init__(self, size):
        # offset by 1 to make indexing easier
        self.board = [None]
        self.board_size = size
    def create_board(self):
        """Create an empty board with dimensions of board_size argument."""
        row = [None] + ([' '] * self.board_size)
        for i in range(self.board_size):
            self.board.append(row)
    def draw_mark(self, choice, player_mark):
        """Draw an x or o on the space chosen by the player if the space is
           unoccupied.
        
           Choice is a list containing the coordinates of the space to place a
           mark [row, column].
           
           Return True if move was valid, return False if not.
        """
        row = choice[0]
        column = choice[1]
        if self.board[row][column] == ' ':
            self.board[row][column] = player_mark
            return True
        else:
            return False
    
oBoard = Board(3)
oBoard.create_board()
oBoard.draw_mark([1, 1], 'x')
print(oBoard.board)

实例化Board对象并调用draw_mark方法后,我期望的输出是:

[None, [None, 'x', ' ', ' '], [None, ' ', ' ', ' '], [None, ' ', ' ', ' ']]

但实际输出为:

[None, ['x', ' ', ' ', ' '], ['x', ' ', ' ', ' '], ['x', ' ', ' ', ' ']]

我曾在Python shell中创建全局网格并直接赋值,能得到预期结果。请问我的类实现中是什么原因导致了这些额外赋值?


问题原因与解决方法

问题出在create_board方法的列表引用逻辑:你只创建了一个row列表对象,随后在循环中多次将这个对象添加到self.board中。这意味着self.board里的所有行本质上都是同一个列表的引用——修改其中任意一行的元素,会同步影响所有行。

解决方法是每次循环都生成一个新的行列表,避免复用同一个对象:

def create_board(self):
    """Create an empty board with dimensions of board_size argument."""
    for i in range(self.board_size):
        # 每次循环创建独立的行列表
        row = [None] + ([' '] * self.board_size)
        self.board.append(row)

修改后,每一行都是独立的列表对象,修改某一行的元素就不会影响其他行了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 14:35:43