首页 文章

python中的2D列表在每个列表中的相同位置更改值[重复]

提问于
浏览
0

这个问题在这里已有答案:

def boardprint():
    array_board = board
    print(
" _ _ _\n"+
"|"+(array_board[0][0])+"|"+(array_board[0][1])+"|"+(array_board[0][2])+"|\n"+
"|_|_|_|\n"+
"|"+(array_board[1][0])+"|"+(array_board[1][1])+"|"+(array_board[1][2])+"|\n"+
"|_|_|_|\n"+
"|"+(array_board[2][0])+"|"+(array_board[2][1])+"|"+(array_board[2][2])+"|\n"+
"|_|_|_|\n"
        )




board=[[" "]*3]*3
move=0


boardprint()
board_full=False
won=False
while (board_full!=True and won!=True):
    move+=1
    move_success=False
    while (move_success==False):
        row_position=int(input("In which row would you like to place a cross?"))
        col_position=int(input("In which column would you like to place a cross?"))
        if (board[col_position][row_position]==" "):
            (board[col_position][row_position])="x"
            move_success=True
        else:
            print("Try again, that position is full")
        boardprint()
    if (move>=9):
        board_full=True
    move+=1
    move_success=False
    while (move_success == False):
        row_position=int(input("In which row would you like to place a nought?"))
        col_position=int(input("In which column would you like to place a nought?"))
        if (board[col_position][row_position]==" "):
            board[col_position][row_position]="o"
            move_success=True
        else:
             print("Try again, that position is full")
        boardprint()

这应该是一个井字游戏 . 然而,当用户在棋盘中输入他们想要的位置时,它会用整个列填充整个列,忽略行 . 我知道一维列表会更容易,但我的Comp Sci老师要我使用2D列表而且他没有不知道为什么会这样 .

1 回答

  • 0

    更换

    board = [[" "]*3]*3
    

    from copy import deepcopy
    board = [deepcopy([' ' for x in range(3)]) for x in range(3)]
    

    应该解决您的问题,但是您的原始问题源于一些深层复制和浅层复制问题,您应该真正红色Dan的链接,因为它解决了您的确切问题 .

    虽然您可以考虑使用用户输入的值 - 1表示他们打算制作的tic tac 2标记的位置 . 例如,如果我输入1,1我可能想在这里放置我的标记:

    _ _ _
    |X| | |
    |_|_|_|
    | | | |
    |_|_|_|
    | | | |
    |_|_|_|
    

    而不一定在这里:

    _ _ _
    | | | |
    |_|_|_|
    | |x| |
    |_|_|_|
    | | | |
    |_|_|_|
    

    那只是我,你的方式很好 .

相关问题