python中的2D列表改变每个lis中相同位置的值

2024-10-03 06:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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老师希望我使用二维列表,他不知道为什么这样做


Tags: inboardfalsetruewhichinputmoveposition
1条回答
网友
1楼 · 发布于 2024-10-03 06:28:27

更换

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

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

你应该解决你的问题,但是你原来的问题源于一些深拷贝和浅拷贝的问题,你真的应该红丹的链接,因为它解决了你的确切问题

尽管您可以考虑使用用户输入的值-1作为他们打算进行的tic-tac-two标记的位置。例如,如果我输入1,1,我可能想在这里做标记:

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

不一定在这里:

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

那只是我,你的方式很好

相关问题 更多 >