我有这个数学问题,我需要从矩阵中选择一个随机元素。现在我有矩阵和其他位的代码。但我尝试使用下面的代码选择一个随机元素,但它总是选择一个完整的行,而不是随机的单个元素。
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)
答案 0 :(得分:3)
def randSelect(self):
row = random.randrange(self.rows)
col = random.randrange(self.cols)
return self.matrix[row][col]
答案 1 :(得分: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)
答案 2 :(得分:0)
您的randselect
函数需要使用两个索引访问self.matrix
。它是一个数组数组,所以只有一组方括号可以得到一个数组。您需要第二次访问才能获得单个元素。
def randSelect(self):
row = self.matrix[random.randrange(len(self.matrix))]
return row[random.randrange(len(row))]
答案 3 :(得分: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