如何从3x3矩阵中选择随机位置

问题描述 投票:0回答:4

我有这个数学问题,我需要从矩阵中选择一个随机元素。现在我有矩阵和其他位的代码。但我尝试使用下面的代码选择一个随机元素,但它总是选择一个完整的行,而不是随机的单个元素。

def randSelect(self):
    return self.matrix[random.randrange(len(self.matrix))]

这是完整的代码

class Matrix():
    def __init__(self, cols, rows):
        self.cols = cols
        self.rows = rows

        self.matrix = []
        for i in range(rows):
            selec_row = []
            for j in range(cols):
                selec_row.append(0)
            self.matrix.append(selec_row)
    def setitem(self, col, row, v): 
        self.matrix[col-1][row-1] = v

    def randSelect(self):
        return self.matrix[random.randrange(len(self.matrix))] 

    def __repr__(self):
        outStr = ""
        for i in range(self.rows):
            outStr += 'Row %s = %s\n' % (i+1, self.matrix[i])
        return outStr

    a = Matrix(3,3)
    a.setitem(1,2,10)
    a.setitem(1,3,15)
    a.setitem(2,1,10)
python matrix random elements
4个回答
3
投票
def randSelect(self):
    row = random.randrange(self.rows)
    col = random.randrange(self.cols)
    return self.matrix[row][col]

1
投票

这是我的解决方案。我使用一个namedtuple作为返回,所以你也可以获得该值的位置。

import random
from collections import namedtuple

RandomValue = namedtuple("RandomValue", ("Value", "RowIndex", "ValueIndex"))


class Matrix():
    def __init__(self, cols, rows):
        self.cols = cols
        self.rows = rows

        self.matrix = []
        for i in range(rows):
            selec_row = []
            for j in range(cols):
                selec_row.append(0)
            self.matrix.append(selec_row)

    def setitem(self, col, row, v):
        self.matrix[col - 1][row - 1] = v

    def randSelect(self):
        row = self.matrix[random.randrange(len(self.matrix))]
        value = random.choice(row)
        return RandomValue(value, self.matrix.index(row), row.index(value))

    def __repr__(self):
        outStr = ""
        for i in range(self.rows):
            outStr += 'Row %s = %s\n' % (i + 1, self.matrix[i])
        return outStr


a = Matrix(3, 3)
a.setitem(1, 2, 10)
a.setitem(1, 3, 15)
a.setitem(2, 1, 10)
print(random_val.RowIndex)
print(random_val.ValueIndex)
print(random_val.Value)

0
投票

你的randselect函数需要使用两个索引访问self.matrix。它是一个数组数组,因此只需要一组方括号就可以得到一个数组。您需要第二次访问才能获得单个元素。

def randSelect(self):
    row = self.matrix[random.randrange(len(self.matrix))]
    return row[random.randrange(len(row))]

0
投票

你可以有一个函数在索引范围内生成随机数,你可以使用这些索引来调用数组中的随机位置

    from random import randint
    i = (randint(0,9)) #assuming your range for i is from 0-9
    j = (randint(0,9)) #assuming your range for j is from 0-9
© www.soinside.com 2019 - 2024. All rights reserved.