2014-01-05 108 views
1

無法修改二維矩陣中str格式的單個元素。初始矩陣元素初始化爲「_」。一些元素將被修改爲「X」。
下面是代碼python中矩陣的str賦值

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 

請提出一個辦法修改單個矩陣字符串元素的一部分。

回答

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)