我遇到了一个函数,但不太理解它。我不确定这是一个惯例还是有什么意义。 _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))))
最佳答案
有关许多 Python 样式约定的详细信息,请参阅 PEP8。特别是,您可以在此处找到单个前导下划线的描述:
https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles
_single_leading_underscore : weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.
在上面的循环中,这有点误用,因为它们只是使用 _p
来避免与现有名称 p
发生冲突。这些变量名显然不太好。 _p
是 enumerate 提供的数组项,而 p
也是整个数组(本地覆盖传入的原始 p
参数) .
顺便说一句,循环本身有点尴尬,可以简化和优化(主要是使用更好的范围而不是pass
,并避免重复重新计算总和)。
关于python - python中字母前的下划线(_p)是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43128988/