我遇到了一个函数,但并不完全理解它。我不确定这是一种惯例还是有意义的。_p是什么,_p在哪里输入的函数。如果你能在这里给我一些关于for循环的解释,我将不胜感激。
def contraction_mapping(S, p, MF, params, beta=0.75, threshold=1e-6, suppr_output=False):
'''
Initialization of the state-transition matrices:
describe the state-transition probabilities if the maintenance cost is incurred,
and regenerate the state to 0 if the replacement cost is incurred.
'''
ST_mat = np.zeros((S, S))
p = np.array(p)
for i in range(S):
for j, _p in enumerate(p):
if i + j < S-1:
ST_mat[i+j][i] = _p
elif i + j == S-1:
ST_mat[S-1][i] = p[j:].sum()
else:
pass
R_mat = np.vstack((np.ones((1, S)),np.zeros((S-1, S)))) 发布于 2017-03-30 21:56:03
有关许多python样式约定的详细信息,请参见PEP8。特别是,您可以在这里找到单个前导下划线的描述:
https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
_single_leading_underscore :弱的“内部使用”指示器。例如,从M导入*不导入名称以下划线开头的对象。
在上面的循环中,这在某种程度上是误用的,因为他们使用_p只是为了避免与现有名称p发生冲突。这些变量名显然不是很好。_p是枚举提供的数组的项,而p也是整个数组(本地重写传入的原始p参数)。
顺便提一句,循环本身有点尴尬,可以简化和优化(主要是使用更好的范围而不是pass,并避免重复计算总和)。
https://stackoverflow.com/questions/43128988
复制相似问题