稀疏随机填充数组的 Pythonic 方法?

标签 python arrays random

问题: 用 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/

相关文章:

java - 将数组插入二维数组

android - picasso 下载随机图像

python - 如何使用类似于 plt.hist 的 matplotlib 绘制 np.histogram 的结果

python - 如何查询打开的持久委托(delegate)项

python - 提高比较算法 np.packbits(A==A[ :, None], axis=1) 的性能

arrays - TableView 仅显示从 Firebase 读取的部分数据

c - 为什么我的随机数组和排序程序不工作?

从列表中随机选择

python - 如何从python中的URL获取域名(名称+TLD)

python - 解读两位数