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

3 投票
2 回答
5057 浏览
提问于 2025-04-18 16:44

我应该如何格式化一个很长的 for in 语句在 Python 中呢?

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

我发现我只能用一个 反斜杠 来换行 for in 语句:

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

但是我的代码检查工具对这种格式有问题,什么才是更符合 Python 风格的写法呢?

2 个回答

5

你可以利用括号内的隐式换行,这在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
3
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

或者把两者结合起来。

撰写回答