在python中,字母前面的下划线是什么意思

2024-05-15 18:53:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到一个函数,但不太理解它。我不确定这是一个惯例或有什么意义。_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))))        

Tags: the函数inforifisnpzeros
1条回答
网友
1楼 · 发布于 2024-05-15 18:53:43

有关许多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,并且避免重复地重新计算总和)。在

相关问题 更多 >