2015-11-10 80 views
2

這是我試圖運行代碼列表索引錯誤類型

import random 
def createBoard(rows, columns, mines): 
    board = [["C" for row in range(rows)],[" " for col in range(columns)]] 
    for i in range(0, mines): 
     board[[int(random.randrange(rows))],[int(random.randrange(columns))]] = "C", "*" 
    return board 
createBoard(9, 12, 10) 
board = board 
print(board) 

這是錯誤我得到

Traceback (most recent call last): 
    File "C:\Users\Josh\Desktop\Python\createBoard.py", line 7, in <module> 
    createBoard(9, 12, 10) 
    File "C:\Users\Josh\Desktop\Python\createBoard.py", line 5, in createBoard 
    board[[int(random.randrange(rows))],[int(random.randrange(columns))]] = "C", "*" 
TypeError: list indices must be integers, not tuple 
+1

'board [[int(random.randrange(rows))],int(random.randrange(columns))]]',在這裏創建一個元組。有兩個列表(一個是'[int(random.randrange(rows))]'',另一個是'[int(random.randrange(columns))]')。 –

回答

2

退房How to define two-dimensional array in python獲取關於Python中二維數組的詳細討論。

基本上,python中的二維數組不能用作board [x,y],它們實際上是數組的陣列,如board [x] [y]。

你要重構你的代碼,使得

for i in range(0, mines): 
     board[[int(random.randrange(rows))],[int(random.randrange(columns))]] = "C", "*" 

看起來更像

for i in range(0, mines): 
    boardfor i in range(0, mines): 
    board[int(random.randrange(rows))][int(random.randrange(columns))]] = "C", "*" 

希望這是有幫助的!