2014-04-03 45 views
2

我使用numPy設置了3x3網格。Python - 從3x3 NP陣列中挑選隨機的列或行

grid = np.array([[1,2,3], 
       [4,5,6], 
       [7,8,9]]) 

我可以在特定的地方,用戶輸入的東西([1,1])將在「5」發生在這個特殊的例子有:

grid[1,1] = input ("Place a number inside") 

我的問題是:如何我可以設置一些選擇RANDOM行/列供玩家輸入的東西,而不是我告訴它「確定放在位置[1,1]。

非常感謝你,祝你有美好的一天。

回答

1

簡單的情況下,使用np.random.randint(0, 3, 2)爲0和3之間使兩個隨機數。然後你可以用這個索引你的數組,如果你把它轉換爲tuple

rand_point = np.random.randint(0, 3, 2) 
grid[tuple(rand_point)] = input("Place a number at %s: " % rand_point) 

或者,你可以分別生成兩個數字(這將是重要的,如果你的陣列是不是正方形):

nrows, ncols = grid.shape #shape tells us the number of rows, cols, etc 
rand_row = np.random.randint(0, nrows) 
rand_col = np.random.randint(0, ncols) 
grid[rand_row, rand_col] = input("Place a number at [%d, %d]: " % (rand_row, rand_col)) 

如果你想要漂亮的,你可以自動完成這一條線,而不必調用randint兩次,即使ncols != nrows

rand_point = tuple(np.random.random(grid.ndim)*grid.shape) 
grid[rand_point] = input("Place a number at [%d, %d]: " % rand_point)