mut*_*lla 1 python for-loop pep8 long-lines
我在 PEP 8 风格指南中找不到答案。是否有可能for通过使用圆括号而不是反斜杠来分解长语句?
以下将导致语法错误:
for (one, two, three, four, five in
one_to_five):
pass
Run Code Online (Sandbox Code Playgroud)
是的,您可以在关键字后面使用括号in:
for (one, two, three, four, five) in (
one_to_five):
pass
Run Code Online (Sandbox Code Playgroud)
在您的问题中,如发布的,您不小心删除了左括号,这导致您收到语法错误。
如果较长的部分是拆包,我会避免它:
for parts in iterable:
one, two, three, four, five, six, seven, eight = parts
Run Code Online (Sandbox Code Playgroud)
或者如果它真的很长:
for parts in iterable:
(one, two, three, four,
five, six, seven, eight) = parts
Run Code Online (Sandbox Code Playgroud)
如果iterable是一个长表达式,您应该在循环之前将其单独放在一行中:
iterable = the_really_long_expression(
eventually_splitted,
on_multiple_lines)
for one, two, three in iterable:
Run Code Online (Sandbox Code Playgroud)
如果两者都很长,那么您可以将这些约定结合起来。