【问题标题】:How to split a line of code into multiple lines?如何将一行代码拆分为多行?
【发布时间】:2015-10-30 15:58:48
【问题描述】:

我必须编写一个程序来使用 3 种不同的算法计算 Pi。 我使用 Chudnovsky 公式作为我的第三个算法,它是一个单行算法。 为了便于阅读,我的老师问我是否可以将它分成多行。

代码如下:

iteration_sum += ((-1)**k)*(Decimal((factorial(6*k)))/(Decimal((factorial(k)**3))*Decimal((factorial(3*k))))*(13591409+545140134*k)/(640320**(3*k)))

如果我能在 ...)))/(Decimal((...

提前感谢您的帮助。

史蒂夫

【问题讨论】:

  • 只需将计算分成几个步骤。并且不要害怕在必要时添加额外的变量并增加可读性。

标签: python split newline


【解决方案1】:

你需要关注pythonPEP 0008 -- Style Guide for Python Code。

更具体地说是Maximum Line Length

将所有行限制为最多 79 个字符。

花点时间阅读并熟悉它。例如:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

注意逗号后面的\,表示下一行继续。

在您的示例中,它归结为偏好,但最好在操作员之后进行:

iteration_sum += ((-1)**k)*(Decimal((factorial(6*k)))/
                            (Decimal((factorial(k)**3))*Decimal((factorial(3*k))))*
                            (13591409+545140134*k)/(640320**(3*k)))

为了便于阅读,额外的缩进表明它们位于((-1)**k)*( 之后。

【讨论】:

  • 这种方法比with open('read') as file_1:with open('written', 'w') as file_2:更可取吗?
【解决方案2】:

您可以在这里找到答案。 http://code.runnable.com/UqBbr4-VwoAMAAUN/how-to-write-multiline-statements-in-python

将您的代码行分成几行并将 \ 放在每行的末尾。

print "this statement " + \
"goes " + \
"beyond " + \
"one " + \
"line " + \
"but gets printed as a single line"

【讨论】:

    【解决方案3】:

    您可以使用 \ 来分割 Python 中的一长行代码。 即:

    result = 1 + 1\
     + 2 * 5\
     - 3.14 * 25
    

    【讨论】:

    • 虽然准确,但这很尴尬并且(在这种情况下)没有必要,更不用说风格指南不鼓励了。
    • 是的,你的权利。但它有效。 :) 愿 Guido van Rossum 原谅我,无论他现在在哪里:/
    • @jonrsharpe 另外,如果您将大型计算拆分为多行,您可以借此机会使用局部变量或单独的函数命名更突出的“块”。它还可以阐明复杂表达式中的运算顺序:return _available(x, y) / _required(x, y) 强调返回值是比任何添加括号组合更好的比率。
    【解决方案4】:

    除了 PEP008,这是 Python 在这些问题上的真理,您可以使用括号内的事实来添加换行符而不需要 \。事实上,这就是接受的答案所使用的机制。

    def foo():
        return (1 + 2 ) / (5 + 6 + 7 - 0.5)
    

    注意下面的代码不是 PEP008 兼容的缩进,只是地址行 分裂。

    def foo2():
    
        #explicit new line with \
        #after you open a parenthesis ( you can add newlines implicitly until )
        return (1 + 2 ) \
            / (5 
            + 6 
            + 7 
            - 0.5)
    
    print foo()
    print foo2()
    
    
    0.171428571429
    0.171428571429
    

    您通常会在选项或字典中看到这一点:

    my_opt = dict(
        choice1=1,
        choice2=2,
        choice3=3,
    )
    

    【讨论】:

      【解决方案5】:

      我通常在下一个参数之前分裂。在您的情况下,它看起来像这样:

      iteration_sum += ((-1)**k)*(Decimal((factorial(6*k)))/
                              (Decimal((factorial(k)**3))*Decimal((factorial(3*k))))*
                              (13591409+545140134*k)/(640320**(3*k)))
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-13
        相关资源
        最近更新 更多