python - 在 Python 中迭代函数的参数(使用 2d numpy 数组和小数列表)
问题描述
我定义了一个带有 2 个参数的函数:一个对称矩阵M
和一个概率值p
。我想定义一个循环遍历我的参数的函数。循环以 0.01 的概率开始,并在到达 时停止p
。M
在每一步,该函数根据概率从矩阵中选择随机行和列并将它们删除。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
解决方案
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)
。
推荐阅读
- c# - 如何在 Unity 中进行这种 3D 摄像机移动?
- javascript - 如何遍历以下代码的对象?
- json - 从 Pandas 列中的 json 数据中提取键值计数
- visual-studio-code - 无法从命令行 WSL ZSH 打开 VSCode
- c++ - c++ 元函数返回一个类型
- php - 在 laravel 6.16 中调用未定义函数 App\Http\Controllers\Auth\array_get()
- javascript - 如何创建一个新的如果前一个块没有可用空间来保留它,则阻止使用 js 粘贴溢出内容
- ethereum - 如何在 Solidity 中声明常量
- c++ - 函数属性应该去哪里?
- python - Python,pd数据框根据条件提取值引发错误