【问题标题】:Python, PEP-8, E122 continuation line missing indentation or outdentedPython、PEP-8、E122 续行缺少缩进或缩进
【发布时间】:2017-09-20 05:13:19
【问题描述】:

我收到这个错误,但是我选择缩进它,我仍然收到它,你知道为什么吗?

if len(argmaxcomp) == 1:
    print "The complex with the greatest mean abundance is: {0}"\
    .format(argmaxcomp[0])

【问题讨论】:

标签: python pep8


【解决方案1】:

一般pep8建议你prefer parenthesis over continuation lines

包装长行的首选方法是在圆括号、方括号和大括号内使用 Python 隐含的续行。通过将表达式括在括号中,可以将长行分成多行。应该优先使用这些,而不是使用反斜杠来续行。

即:

if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is: {0}"
          .format(argmaxcomp[0]))

另一种选择,是使用 python 3 的打印:

from __future__ import print_function

if len(argmaxcomp) == 1:
    print("The complex with the greatest mean abundance is:", argmaxcomp[0])

注意:print_function 可能会中断/需要更新其余代码...在您使用过 print 的任何地方。

【讨论】:

    【解决方案2】:

    我没有收到上述错误,但我尝试了以下类型, 有错误请发帖,以便我们检查

    In [6]: argmaxcomp = [100]
    
    In [7]: if len(argmaxcomp) == 1:
       ...:     print 'val: {0}'\
       ...:     .format(argmaxcomp[0])
       ...:     
    val: 100
    
    In [8]: if len(argmaxcomp) == 1:
       ...:     print 'val: {0}'.format(argmaxcomp[0])
       ...:     
    val: 100
    
    In [9]: if len(argmaxcomp) == 1:
       ...:     print 'val: {0}'.format(
       ...:     argmaxcomp[0])
       ...:     
    val: 100
    

    【讨论】:

      【解决方案3】:

      one section in the PEP8 写着:

      包装长行的首选方法是在圆括号、方括号和大括号内使用 Python 隐含的续行。通过将表达式括在括号中,可以将长行分成多行。应该优先使用这些,而不是使用反斜杠来续行。

      反斜杠有时可能仍然合适。例如,长的、多个 with 语句不能使用隐式延续,所以反斜杠是可以接受的

      这意味着(即使这与 PEP8-E122 无关)您应该将其包裹在括号中而不是使用反斜杠,然后隐式续行(缩进)是左括号:

      if len(argmaxcomp) == 1:
          print("The complex with the greatest mean abundance is: {0}"
                .format(argmaxcomp[0]))
      #         ^--------- The bracket opens here
      

      只提到了 2 个例外,其中反斜杠是可以接受的,因为括号是不可能的(因为它们在这些上下文中具有其他含义):

      • 多-with
      • asserts

      但是,如果您真的想要那个反斜杠(仅适用于 python2),它应该与第一个表达式具有相同的缩进:

      if len(argmaxcomp) == 1:
          print "The complex with the greatest mean abundance is: {0}" \
                .format(argmaxcomp[0])
      #         ^--------- The first expression starts here
      

      【讨论】:

        【解决方案4】:

        这种情况下的问题是根本没有缩进 显然错误发生在最后一行。 如果括号不是一个选项,只需添加如下缩进:

        if len(argmaxcomp) == 1:
            print "The complex with the greatest mean abundance is: {0}" \
                .format(argmaxcomp[0])
        

        任何数量的空格都可以,但我不知道什么是首选。

        【讨论】:

          【解决方案5】:

          刚刚遇到类似问题并解决了。我认为 OP 代码的问题在于续行之间可能存在空格。除了 \n 之外应该什么都没有。

          【讨论】:

            猜你喜欢
            • 2021-09-29
            • 2020-01-14
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-25
            • 1970-01-01
            • 2014-05-26
            相关资源
            最近更新 更多