在python中,如何在一行中用1或0随机填充矩阵?

在python中,如何在一行中用1或0随机填充矩阵?,python,numpy,Python,Numpy,我编写了一个代码,用0或1随机填充一个矩阵。但它以4-5行结束。我想让它排成一行 pop_size = (8,10) initial_pop = np.empty((pop_size)) for i in range(pop_size[0]): for j in range(pop_size[1]): initial_pop[i][j] = rd.randint(0,1) 我知道您正在使用NumPy。如果是,那么答案是: np.random.randint(2,

我编写了一个代码,用0或1随机填充一个矩阵。但它以4-5行结束。我想让它排成一行

pop_size = (8,10)
initial_pop = np.empty((pop_size))
for i in range(pop_size[0]):
     for j in range(pop_size[1]):
          initial_pop[i][j] = rd.randint(0,1)

我知道您正在使用
NumPy
。如果是,那么答案是:

np.random.randint(2, size=pop_size)
以下是有关此例程的NumPy docs文章:。 Numpy有很好的文档记录,下次尝试自己检查文档


编辑:参数应该是2,而不是1。在标准Python中,请尝试:

from random import randint
x = [[randint(0,1) for _ in range(8)] for _ in range(10)]

使用numpy的
randint
方法

matrix = np.random.randint(2, size=pop_size)

请在以下网址查看答案:

可以使用numPy轻松填充矩阵

e、 g:

3x3矩阵:

import numpy as np
my_matrix = np.random.randint(2,size=3)

output = ([[0,1,0],
          [0,0,1],
          [1,0,1]])
文件:

如果您希望阵列中只有1或0,可以通过以下方法实现

    import numpy as np
    np.zeros(2,2) #it will create [2,2] matrix with all zeros
    np.ones(2,2)  #it will create [2,2] matrix with all ones

你不能理解你的问题,能解释得更清楚些吗?
np.random.randint()
?使用
np.random.randint(2,(8,10))
使用
1
将不起作用。第一个参数必须为
2
。否则到处都会有
0
s。@hqkhan你说得对。它与python的
random.randint
不一致,后者的上限是包含在内的。