2014-04-03 42 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)