如何将一行代码拆分成多行?

How to split a line of code into multiple lines?

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

代码如下所示:

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

如果我能在...之后分割它就太好了)))/(小数((...

提前感谢您的帮助。

史蒂夫

您需要关注 python PEP 0008 -- Style Guide for Python Code.

更具体地说 Maximum Line Length

Limit all lines to a maximum of 79 characters.

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

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)*( 之后。

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

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

我通常会在下一次争论之前分手。在您的情况下,它看起来像这样:

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

希望对您有所帮助。

您可能会在这里找到答案。 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"

除了 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,
)