strthon中的str赋值

时间:2014-01-05 06:53:42

标签: python matrix

无法在二维矩阵中修改str格式的单个元素。初始矩阵元素初始化为" _"。一些元素将被修改为" X"。
这是代码的一部分

board=[]  
for i in range(3):  
        board+=['_'*3]  
        board[i]=" ".join(board[i])  
        print(board[i])  
def game_board(board):  
    for i in range(3):  
        board[i]="".join(board[i])  
        print(board[i])  
j=0  
while(j<=8):  
    while(j%2==0):  
        print("First player's turn")  
        row=int(input("Row="))  
        col=int(input("Column="))  
        while(board[int(col)-1][2*int(row)-2]!='_'):  
            print("Wrong Input")  
            row=int(input("Row="))  
            col=int(input("Column="))  
        else:  
            board[int(col)-1][2*(int(row)-1)]='X'  
            print(game_board(board))  
            print(board)  
            j+=1  
    else:  
        print("Second player's turn")  
        row=int(input("Row="))  
        col=int(input("Column="))  
        while(board[int(col)-1][2*int(row)-2]!="_"):  
            print("Wrong Input")  
            row=int(input("Row="))  
            col=int(input("Column="))  
        else:  
            board[int(col)-1][2*int(row)-2]=="O"  
            print(game_board(board))  
            j+=1

请建议修改单个矩阵字符串元素的方法。

1 个答案:

答案 0 :(得分:0)

在您准备好打印之前,只需将您的主板保留为列表清单:

def print_board(board):
    for row in board:
        print ' '.join(row)

def game_board(width, height):
    return [['_' for i in xrange(width)] for j in xrange(height)]

board = game_board(3,3)

board[0][2] = 'X'
board[1][1] = 'X'

print_board( board )