在python中查找0和1的随机矩阵,其中1的数量有限

acruukt9  于 2023-04-28  发布在  Python
关注(0)|答案(2)|浏览(151)

我在python中生成一个0和1的矩阵

poblacionCandidata = np.random.randint(0, 2, size=(4, 2))

但是,我需要它在每一行中最多只有两个1。
我已经检查了this question,但它对我来说太复杂了。
有人能帮我吗
结果应该类似于

[[1 1 0 0]
 [1 0 0 1]
 [1 0 0 0]
 [0 1 0 0]]

最好的问候

vmpqdwk3

vmpqdwk31#

你可以使用一个循环:

import numpy as np

def generate_matrix(rows: int, cols: int, max_ones_per_row: int) -> np.ndarray:
    """
    Generate a matrix with up to a specified number of ones per row.
    
    :param rows: The number of rows in the matrix.
    :param cols: The number of columns in the matrix.
    :param max_ones_per_row: The maximum number of ones to be placed in each row.
    :return: A numpy array representing the generated matrix.
    """
    matrix = np.zeros((rows, cols), dtype=int)
    for i in range(rows):
        ones_per_row = np.random.randint(0, max_ones_per_row + 1)
        ones_indices = np.random.choice(cols, ones_per_row, replace=False)
        matrix[i, ones_indices] = 1
    return matrix

poblacionCandidata = generate_matrix(rows=4, cols=4, max_ones_per_row=2)
print(poblacionCandidata)

输出示例:

[[1 0 0 0]
 [0 0 1 1]
 [0 0 0 0]
 [0 1 0 0]]
olmpazwi

olmpazwi2#

最后,我设法创建了一个函数

def generacionPoblacionCandidata(tamanioPoblacion, numColumnas, n):
    poblacionCandidata = np.zeros((tamanioPoblacion, numColumnas), dtype=int)
    for j in range(numColumnas):
        contador_unos = 0
        while contador_unos < n:
            columna_aleatoria = np.random.randint(0, 2, size=tamanioPoblacion)
            if np.sum(columna_aleatoria) <= n:
                poblacionCandidata[:, j] = columna_aleatoria
                contador_unos = np.sum(columna_aleatoria)
    return poblacionCandidata

我已经测试过了,似乎工作正常

相关问题