def get_output(shape, n):
Z = np.zeros(shape)
while np.sum(Z)<n:
Z[np.random.randint(0,shape[0]),np.random.randint(0,shape[1])] = 1
return Z
get_output((5,5), 10)
from random import shuffle
def randomNumbers():
l=[1 for _ in range(10)]+[0 for _ in range(15)]
shuffle(l)
lst=[]
for i in range(0,25,5):
lst.append(l[i:i+5])
return lst
from random import sample
width = 5
height = 5
sample_size = 10
assert sample_size <= width * height
matrix = [[0] * width for _ in range(height)]
for x, y in sample([(x, y) for x in range(width) for y in range(height)], k=sample_size):
matrix[y][x] = 1
for row in matrix:
print(row)
也许可以试试这个(使用NumPy):
你可以这样做
一种方法是从一个二维列表开始,其中填充零,然后选择十个不同的坐标,在其中插入一个:
输出:
相关问题 更多 >
编程相关推荐