创建一个 5 x 5 的矩阵,其中 5 个随机分布

Create a 5 by 5 matrix with 5 ones randomly distributed

这是我试过的代码。如果只想要5个随机分布在里面怎么修改呢?

import numpy as np
mat = np.random.randint(2,size=(5,5))
>>> import numpy as np
>>> import random
>>> mat = np.zeros(5*5)
>>> indices = random.sample(range(5*5), 5)
>>> mat[indices] = 1
>>> mat = mat.reshape(5, 5)
>>> mat
array([[0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 1.],
       [0., 0., 1., 0., 0.],
       [1., 0., 1., 0., 1.],
       [0., 0., 0., 0., 0.]])

我已经明确使用了 5*5。您可以将 25 放在那里,或者 N*M 或类似的。

您也可以使用 NumPy 随机模块,但是 Python stdlib random 模块在这里使用起来很容易。

由于有时评论可能包含出色的答案,但可能会隐藏(或完全删除),因此我将 Michael Szczesny 提供的解决方案放在这里:

>>> mat = np.random.permutation(np.eye(5, dtype=int).ravel()).reshape(5,5)
>>> mat
array([[0, 0, 0, 0, 0],
       [0, 1, 0, 0, 0],
       [1, 1, 0, 0, 0],
       [0, 0, 1, 1, 0],
       [0, 0, 0, 0, 0]])