python - python中字母前的下划线(_p)是什么意思

标签 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))))        

最佳答案

有关许多 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/

相关文章:

python - 使用 SURF 和 FLANN 比较图像与图像数据库

python - 如何按日期对 pandas 数据框进行排序

Python:在满足特定条件时跳过代码块(计算)而不使用 "if"语句

python - 如何以十六进制字节解包/解码十六进制字符串?

python - Raspberry - 发送 CAN 消息

python - 尝试将类(在列表中)保存到文件中

javascript - 如何将JS日期字符串转换为django日期时间格式?

python - 我无法通过我的 View 保存对象。多值字典键错误

python - 为什么会出现 AttributeError : module 'networkx' has no attribute 'average_neighbor_in_degree' ?

c++ - Python Swig 包装器 : how access underlying PyObject