Python,PEP-8,E122:缺少缩进或超出缩进的连续行

12

我遇到了这个错误,无论我如何缩进它,它仍然存在,你知道是为什么吗?

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

3
MCVE,请提供最小化、完整、可重现的例子,以便更好地理解和解决程序问题。 - sam
5个回答

9

通常,pep8建议您使用括号而不是续行符

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

也就是说:

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

另一种选择是使用Python 3的print函数:
from __future__ import print_function

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

注意:print_function可能会破坏或需要更新其余代码...无论您在哪里使用了print。

1
在这种情况下,问题在于根本没有缩进,而显然错误发生在最后一行。 如果括号不是一个选项,只需添加缩进,如下所示:
if len(argmaxcomp) == 1:
    print "The complex with the greatest mean abundance is: {0}" \
        .format(argmaxcomp[0])

任意数量的空格都可以使用,但我不知道哪种更受欢迎。

0

刚刚遇到了类似的问题并解决了它。我认为OP代码的问题可能是连续行之间可能有空格。那里应该什么也没有,只有\n。


0

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

只有两种情况下可以接受反斜杠,因为在这些上下文中括号是不可能的(因为它们在这些上下文中具有其他含义):

  • 多个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

0

我没有遇到上述错误,但我尝试了以下类型,请附带错误信息以便我们检查。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接