python多行[ for in ]语句的正确格式

fdx2calv  于 2023-01-08  发布在  Python
关注(0)|答案(2)|浏览(144)

在python中,我应该如何格式化一个长的for in语句?

for param_one, param_two, param_three, param_four, param_five in get_params(some_stuff_here, and_another stuff):

我发现我只能用一个反斜杠来阻止语句中的for:

for param_one, param_two, param_three, param_four, param_five \
in get_params(some_stuff_here, and_another_stuff):

但是我的linter在这种格式上有问题,什么是像这样格式化语句的 * Python * 方式?

5w9g7ksd

5w9g7ksd1#

您可以利用括号内的隐式行连接(如PEP-8中推荐的):

for (param_one, param_two, 
     param_three, param_four, 
     param_five) in get_params(some_stuff_here, 
                               and_another stuff):

(显然,您可以选择每行的长度以及是否需要在每组括号中包括换行符。)
8+年后再看这篇文章,我会在一开始就把长长的单条逻辑线拆开,而不是试图把整个东西拆成多条物理线,例如(很像@poke所做的),

for t in get_params(some_stuff_here,
                    and_other_stuff):
    (param_one,
     param_two,
     param_three,
     param_four, param_five) = t
c9qzyr3d

c9qzyr3d2#

all_params = get_params(some_stuff_here, and_another_stuff)
for param_one, param_two, param_three, param_four, param_five in all_params:
    pass

或者你可以在循环中移动目标列表:

for params in get_params(some_stuff_here, and_another_stuff):
    param_one, param_two, param_three, param_four, param_five = params
    pass

或者合并。

相关问题