首页 > 解决方案 > 在 Python 中迭代函数的参数(使用 2d numpy 数组和小数列表)

问题描述

我定义了一个带有 2 个参数的函数:一个对称矩阵M和一个概率值p。我想定义一个循环遍历我的参数的函数。循环以 0.01 的概率开始,并在到达 时停止pM在每一步,该函数根据概率从矩阵中选择随机行和列并将它们删除。M然后以增加的概率对新的做同样的事情。我无法使用我的代码获得结果

支持小数的范围函数

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

标签: pythonloopsnumpymatrixiteration

解决方案


M像这样,你只返回p你的第一个索引,i=0.01这是因为一旦你返回一些东西,循环就会停止。另外,你可以range在 python 中使用给定的,你的第一个函数是多余的。例如,我建议您使用列表返回矩阵和索引(您也可以使用 np.arrays 执行此操作)。

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

如果您还想包括概率p,那么您必须循环遍历 range(0.01, p+0.01, 0.01)


推荐阅读