简体   繁体   English

创建具有随机位置的矩阵

[英]Create a Matrix with random position

I am creating a matrix with this 我正在用这个创建矩阵

def letsplay(m,n):
    matrix = [[ '.' for m in range(10)] for n in range(10)]
    for sublist in matrix:
        s = str(sublist)
        s = s.replace('[', '|').replace(']', '|').replace(',', "")
        print(s)

that returns 返回

>>> '.'.'.'.'.'.'.'.'.'.'
    '.'.'.'.'.'.'.'.'.'.'
    ...
    ...

That creats a matrix 10x10. 这将创建一个10x10的矩阵。 and Now I want to add within the matrix to random position with a probability = prob, the prob should be entered by the user, and return for the random posstions a 'N'. 现在,我想以概率= prob在矩阵内添加到随机位置,该prob应该由用户输入,并为随机位置返回“ N”。

How about using a probability matrix: 如何使用概率矩阵:

probs = numpy.random.random_sample((10, 10))
data = numpy.empty(probs.shape, dtype='S1')
data.fill('.')
data[probs < threshold] = 'N'

where threshold is a variable that you choose, for example, 0.05 for a 5% chance. 其中threshold是您选择的变量,例如0.05表示有5%的机会。

Not quite sure what prob=5 would mean, probabilities range from 0 to 1? 不太确定prob = 5意味着什么,概率范围是0到1? I think there's two parts to your question. 我认为您的问题有两个部分。

  • change a random element of the matrix 更改矩阵的随机元素

    matrix[random.randrange(10)][random.randrange(10)] = 'N'

  • have a number of elements changed in the matrix, based on a probability. 根据概率在矩阵中更改许多元素。

     import random prob = 0.01 numNs = prob*10*10 # because eg 1% chance in 10x10 matrix = 1 field for i in range(numNs): changed = False while not changed: x = random.randrange(10) y = random.randrange(10) if not matrix[x][y] == 'N': # if not already changed matrix[x][y] = 'N' changed = True 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM