问题: 用 10 个 1、20 个 2、30 个 3 随机填充一个 10 x 10 的零数组。
我实际上不必使用数组,而我只需要值所在位置的坐标。只是从数组的角度更容易想到。
我为此编写了多个解决方案,但它们似乎都不是直截了当的,也不是 Python 式的。我希望有人能给我一些见识。我的方法是使用一个0--99的线性数组,随机选择(np.random.choice)10个值,将它们从数组中移除,然后选择20个随机值。之后,我将线性位置转换为 (y,x) 坐标。
import numpy as np
dim = 10
grid = np.arange(dim**2)
n1 = 10
n2 = 20
n3 = 30
def populate(grid, n, dim):
pos = np.random.choice(grid, size=n, replace=False)
yx = np.zeros((n,2))
for i in xrange(n):
delPos = np.where(grid==pos[i])
grid = np.delete(grid, delPos)
yx[i,:] = [np.floor(pos[i]/dim), pos[i]%dim]
return(yx, grid)
pos1, grid = populate(grid, n1, dim)
pos2, grid = populate(grid, n2, dim)
pos3, grid = populate(grid, n3, dim)
额外 假设当我填充 1 时,我希望它们都在“数组”的一半上。我可以使用我的方法(从网格 [dim**2/2:] 采样)来做到这一点,但我还没有想出如何对其他建议做同样的事情。
最佳答案
您可以创建所有坐标的列表,shuffle
该列表并取其中的前 60 个 (10 + 20 + 30):
>>> import random
>>> coordinates = [(i, j) for i in xrange(10) for j in xrange(10)]
>>> random.shuffle(coordinates)
>>> coordinates[:60]
[(9, 5), (6, 9), (1, 5), ..., (0, 2), (5, 9), (2, 6)]
然后您可以使用前 10 个插入 10 个值,接下来的 20 个插入 20 个值,其余的插入 30 个值。
关于稀疏随机填充数组的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19687800/