迭代函数';Python中的s参数(使用2d numpy数组和小数列表)
我定义了一个包含两个参数的函数:对称矩阵迭代函数';Python中的s参数(使用2d numpy数组和小数列表),python,loops,numpy,matrix,iteration,Python,Loops,Numpy,Matrix,Iteration,我定义了一个包含两个参数的函数:对称矩阵M和概率值p。我想定义一个在我的参数上循环的函数。循环以概率0.01开始,当达到p时停止。在每一步中,函数根据概率从矩阵M中随机选取行和列,并将其删除。然后以递增的概率对新的M执行相同的操作。我无法使用我的代码获得结果 支持小数的范围函数 这样,对于第一个索引,i=0.01,只返回M和p,这是因为一旦返回某个内容,循环就会停止。此外,由于可以使用python中给定的range,因此第一个函数是多余的。我建议您使用列表返回矩阵和索引(您也可以使用np.arr
M
和概率值p
。我想定义一个在我的参数上循环的函数。循环以概率0.01开始,当达到p
时停止。在每一步中,函数根据概率从矩阵M
中随机选取行和列,并将其删除。然后以递增的概率对新的M
执行相同的操作。我无法使用我的代码获得结果
支持小数的范围函数
这样,对于第一个索引,
i=0.01
,只返回M
和p
,这是因为一旦返回某个内容,循环就会停止。此外,由于可以使用python中给定的range
,因此第一个函数是多余的。我建议您使用列表返回矩阵和索引(您也可以使用np.array)
如果您还希望包含概率p
,则必须循环执行
范围(0.01,p+0.01,0.01)
def frange(start, end, step):
tmp = start
while tmp < end:
yield tmp
tmp += step
def loop(M, p):
for i in frange(0.01, p, 0.01):
indices = random.sample(range(np.shape(M)[0]),
int(round(np.shape(M)[0] * i)))
M = np.delete(M, indices, axis=0) # removes rows
M = np.delete(M, indices, axis=1) # removes columns
return M, indices
def loop(M, p):
mat_list = []
indices_list = []
for i in range(0.01, p, 0.01):
indices = random.sample(range(np.shape(M)[0]),
int(round(np.shape(M)[0] * i)))
M = np.delete(M, indices, axis=0) # removes rows
M = np.delete(M, indices, axis=1) # removes columns
mat_list.append(M)
indices_list.append(indices)
return mat_list, indices_list