用条件随机填充2d矩阵

时间:2016-06-10 19:11:33

标签: python matrix random-sample choice

这是我的情况,我只是把它扔到那里以获得如何处理它的想法。

我有类别categories = [0, 1, 3]10 x 5矩阵,A

如何使用类别中的随机选项填充矩阵A,使得每列必须具有一个且仅出现一次' 0'并且只有一次出现' 1' ?

我的思维过程是:

For each column, Cj, 
    create list L = selection of random integers between [0,9] ( no replacement) 
    Set Cj[k[0]] = 0 and Cj[k[1]] = 1 
    Set Cj[k[i]] , i=2, ..,9

有没有人有更好的方法来解决这个问题?

2 个答案:

答案 0 :(得分:2)

假设您已经拥有矩阵,这是一种方法。 (问题是填充矩阵,而不是创建矩阵)

import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
newMatrix = []

for row in matrix:
    tempRow = restrictedNumbers #first add the restricted numbers since they must appear once
    while len(tempRow) < len(row): #keep adding numbers from unrestricted till lengths are equal
        tempRow.append(random.choice(unrestrictedNumbers))
    random.shuffle(tempRow) 
    newMatrix.append(tempRow[:]) #finally add the shuffled row to newMatrix
pprint.pprint(newMatrix)

这给出了输出:(显然会因随机而变化)

[[3, 1, 3, 0, 3],
 [3, 3, 0, 1, 3],
 [0, 3, 1, 3, 3],
 [0, 3, 1, 3, 3],
 [3, 3, 0, 3, 1],
 [0, 1, 3, 3, 3],
 [1, 0, 3, 3, 3],
 [1, 3, 0, 3, 3],
 [3, 3, 0, 3, 1],
 [3, 0, 1, 3, 3]]

您可以看到每一行都有一个0和一个1

这是一个更短的方式:

import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
newMatrix = []
for row in matrix:
    row = restrictedNumbers + [random.choice(unrestrictedNumbers) for _ in range(len(row)-len(restrictedNumbers))]
    random.shuffle(row)
    newMatrix.append(row)
pprint.pprint(newMatrix)



甚至更短(如果random.shuffle返回列表而不是随机播放,这将是一行)

import pprint
import random

categories = [0,1,3] #complete pool of numbers
restrictedNumbers = [0, 1] #numbers to only appear once
unrestrictedNumbers = [num for num in categories if num not in restrictedNumbers] #can appear any number of times

matrix = [[0, 0, 0, 0, 0] for l in range(10)] #10 rows, 5 columns matrix of zeros
def returnShuffled(startList):
    random.shuffle(startList)
    return startList

newMatrix = [returnShuffled(restrictedNumbers + [random.choice(unrestrictedNumbers) for _ in range(len(row) - len(restrictedNumbers))]) for row in matrix]
pprint.pprint(newMatrix)

答案 1 :(得分:1)

你的问题有点模糊。请提供您在其他职位上可以拥有的更多详细信息。如果一个位置为0且1个位置为1而其他位置可以是任何位置,则使用此位置。

制作一个数组[number_of_columns] = {0,1,2,2,....,2],将它随机播放。然后对于列中的每个位置(i)if (array[i] = 0){array_you_are_making[i]=0};if(array[i] = 1){array_you_are_making[i]=1};if(array[i] = 2){array_you_are_making[i]="do something"};

听起来像Python shuffle()方法的情况。